Edit on GitHub

sqlglot.generator

   1from __future__ import annotations
   2
   3import logging
   4import re
   5import typing as t
   6from collections import defaultdict
   7from functools import reduce, wraps
   8
   9from sqlglot import exp
  10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages
  11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get
  12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS
  13from sqlglot.time import format_time
  14from sqlglot.tokens import TokenType
  15
  16if t.TYPE_CHECKING:
  17    from sqlglot._typing import E
  18    from sqlglot.dialects.dialect import DialectType
  19
  20    G = t.TypeVar("G", bound="Generator")
  21    GeneratorMethod = t.Callable[[G, E], str]
  22
  23logger = logging.getLogger("sqlglot")
  24
  25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)")
  26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
  27
  28
  29def unsupported_args(
  30    *args: t.Union[str, t.Tuple[str, str]],
  31) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
  32    """
  33    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
  34    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
  35    """
  36    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
  37    for arg in args:
  38        if isinstance(arg, str):
  39            diagnostic_by_arg[arg] = None
  40        else:
  41            diagnostic_by_arg[arg[0]] = arg[1]
  42
  43    def decorator(func: GeneratorMethod) -> GeneratorMethod:
  44        @wraps(func)
  45        def _func(generator: G, expression: E) -> str:
  46            expression_name = expression.__class__.__name__
  47            dialect_name = generator.dialect.__class__.__name__
  48
  49            for arg_name, diagnostic in diagnostic_by_arg.items():
  50                if expression.args.get(arg_name):
  51                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
  52                        arg_name, expression_name, dialect_name
  53                    )
  54                    generator.unsupported(diagnostic)
  55
  56            return func(generator, expression)
  57
  58        return _func
  59
  60    return decorator
  61
  62
  63class _Generator(type):
  64    def __new__(cls, clsname, bases, attrs):
  65        klass = super().__new__(cls, clsname, bases, attrs)
  66
  67        # Remove transforms that correspond to unsupported JSONPathPart expressions
  68        for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS:
  69            klass.TRANSFORMS.pop(part, None)
  70
  71        return klass
  72
  73
  74class Generator(metaclass=_Generator):
  75    """
  76    Generator converts a given syntax tree to the corresponding SQL string.
  77
  78    Args:
  79        pretty: Whether to format the produced SQL string.
  80            Default: False.
  81        identify: Determines when an identifier should be quoted. Possible values are:
  82            False (default): Never quote, except in cases where it's mandatory by the dialect.
  83            True or 'always': Always quote.
  84            'safe': Only quote identifiers that are case insensitive.
  85        normalize: Whether to normalize identifiers to lowercase.
  86            Default: False.
  87        pad: The pad size in a formatted string. For example, this affects the indentation of
  88            a projection in a query, relative to its nesting level.
  89            Default: 2.
  90        indent: The indentation size in a formatted string. For example, this affects the
  91            indentation of subqueries and filters under a `WHERE` clause.
  92            Default: 2.
  93        normalize_functions: How to normalize function names. Possible values are:
  94            "upper" or True (default): Convert names to uppercase.
  95            "lower": Convert names to lowercase.
  96            False: Disables function name normalization.
  97        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
  98            Default ErrorLevel.WARN.
  99        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
 100            This is only relevant if unsupported_level is ErrorLevel.RAISE.
 101            Default: 3
 102        leading_comma: Whether the comma is leading or trailing in select expressions.
 103            This is only relevant when generating in pretty mode.
 104            Default: False
 105        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
 106            The default is on the smaller end because the length only represents a segment and not the true
 107            line length.
 108            Default: 80
 109        comments: Whether to preserve comments in the output SQL code.
 110            Default: True
 111    """
 112
 113    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
 114        **JSON_PATH_PART_TRANSFORMS,
 115        exp.AllowedValuesProperty: lambda self,
 116        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
 117        exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"),
 118        exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "),
 119        exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"),
 120        exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
 121        exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}",
 122        exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}",
 123        exp.CaseSpecificColumnConstraint: lambda _,
 124        e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
 125        exp.Ceil: lambda self, e: self.ceil_floor(e),
 126        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
 127        exp.CharacterSetProperty: lambda self,
 128        e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
 129        exp.ClusteredColumnConstraint: lambda self,
 130        e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})",
 131        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
 132        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
 133        exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}",
 134        exp.CopyGrantsProperty: lambda *_: "COPY GRANTS",
 135        exp.CredentialsProperty: lambda self,
 136        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
 137        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
 138        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
 139        exp.DynamicProperty: lambda *_: "DYNAMIC",
 140        exp.EmptyProperty: lambda *_: "EMPTY",
 141        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
 142        exp.EphemeralColumnConstraint: lambda self,
 143        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
 144        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
 145        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
 146        exp.Except: lambda self, e: self.set_operations(e),
 147        exp.ExternalProperty: lambda *_: "EXTERNAL",
 148        exp.Floor: lambda self, e: self.ceil_floor(e),
 149        exp.GlobalProperty: lambda *_: "GLOBAL",
 150        exp.HeapProperty: lambda *_: "HEAP",
 151        exp.IcebergProperty: lambda *_: "ICEBERG",
 152        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
 153        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
 154        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
 155        exp.Intersect: lambda self, e: self.set_operations(e),
 156        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
 157        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
 158        exp.LanguageProperty: lambda self, e: self.naked_property(e),
 159        exp.LocationProperty: lambda self, e: self.naked_property(e),
 160        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
 161        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
 162        exp.NonClusteredColumnConstraint: lambda self,
 163        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
 164        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
 165        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
 166        exp.OnCommitProperty: lambda _,
 167        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
 168        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
 169        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
 170        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
 171        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
 172        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
 173        exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression),
 174        exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression),
 175        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
 176        exp.ProjectionPolicyColumnConstraint: lambda self,
 177        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
 178        exp.RemoteWithConnectionModelProperty: lambda self,
 179        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
 180        exp.ReturnsProperty: lambda self, e: (
 181            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
 182        ),
 183        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
 184        exp.SecureProperty: lambda *_: "SECURE",
 185        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
 186        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
 187        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
 188        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
 189        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
 190        exp.SqlReadWriteProperty: lambda _, e: e.name,
 191        exp.SqlSecurityProperty: lambda _,
 192        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
 193        exp.StabilityProperty: lambda _, e: e.name,
 194        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
 195        exp.StreamingTableProperty: lambda *_: "STREAMING",
 196        exp.StrictProperty: lambda *_: "STRICT",
 197        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
 198        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
 199        exp.TemporaryProperty: lambda *_: "TEMPORARY",
 200        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
 201        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
 202        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
 203        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
 204        exp.TransientProperty: lambda *_: "TRANSIENT",
 205        exp.Union: lambda self, e: self.set_operations(e),
 206        exp.UnloggedProperty: lambda *_: "UNLOGGED",
 207        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
 208        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
 209        exp.Uuid: lambda *_: "UUID()",
 210        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
 211        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
 212        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
 213        exp.VolatileProperty: lambda *_: "VOLATILE",
 214        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
 215        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
 216        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
 217        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
 218        exp.ForceProperty: lambda *_: "FORCE",
 219    }
 220
 221    # Whether null ordering is supported in order by
 222    # True: Full Support, None: No support, False: No support for certain cases
 223    # such as window specifications, aggregate functions etc
 224    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
 225
 226    # Whether ignore nulls is inside the agg or outside.
 227    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
 228    IGNORE_NULLS_IN_FUNC = False
 229
 230    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
 231    LOCKING_READS_SUPPORTED = False
 232
 233    # Whether the EXCEPT and INTERSECT operations can return duplicates
 234    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
 235
 236    # Wrap derived values in parens, usually standard but spark doesn't support it
 237    WRAP_DERIVED_VALUES = True
 238
 239    # Whether create function uses an AS before the RETURN
 240    CREATE_FUNCTION_RETURN_AS = True
 241
 242    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
 243    MATCHED_BY_SOURCE = True
 244
 245    # Whether the INTERVAL expression works only with values like '1 day'
 246    SINGLE_STRING_INTERVAL = False
 247
 248    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
 249    INTERVAL_ALLOWS_PLURAL_FORM = True
 250
 251    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
 252    LIMIT_FETCH = "ALL"
 253
 254    # Whether limit and fetch allows expresions or just limits
 255    LIMIT_ONLY_LITERALS = False
 256
 257    # Whether a table is allowed to be renamed with a db
 258    RENAME_TABLE_WITH_DB = True
 259
 260    # The separator for grouping sets and rollups
 261    GROUPINGS_SEP = ","
 262
 263    # The string used for creating an index on a table
 264    INDEX_ON = "ON"
 265
 266    # Whether join hints should be generated
 267    JOIN_HINTS = True
 268
 269    # Whether table hints should be generated
 270    TABLE_HINTS = True
 271
 272    # Whether query hints should be generated
 273    QUERY_HINTS = True
 274
 275    # What kind of separator to use for query hints
 276    QUERY_HINT_SEP = ", "
 277
 278    # Whether comparing against booleans (e.g. x IS TRUE) is supported
 279    IS_BOOL_ALLOWED = True
 280
 281    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
 282    DUPLICATE_KEY_UPDATE_WITH_SET = True
 283
 284    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
 285    LIMIT_IS_TOP = False
 286
 287    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
 288    RETURNING_END = True
 289
 290    # Whether to generate an unquoted value for EXTRACT's date part argument
 291    EXTRACT_ALLOWS_QUOTES = True
 292
 293    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
 294    TZ_TO_WITH_TIME_ZONE = False
 295
 296    # Whether the NVL2 function is supported
 297    NVL2_SUPPORTED = True
 298
 299    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
 300    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
 301
 302    # Whether VALUES statements can be used as derived tables.
 303    # MySQL 5 and Redshift do not allow this, so when False, it will convert
 304    # SELECT * VALUES into SELECT UNION
 305    VALUES_AS_TABLE = True
 306
 307    # Whether the word COLUMN is included when adding a column with ALTER TABLE
 308    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
 309
 310    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
 311    UNNEST_WITH_ORDINALITY = True
 312
 313    # Whether FILTER (WHERE cond) can be used for conditional aggregation
 314    AGGREGATE_FILTER_SUPPORTED = True
 315
 316    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
 317    SEMI_ANTI_JOIN_WITH_SIDE = True
 318
 319    # Whether to include the type of a computed column in the CREATE DDL
 320    COMPUTED_COLUMN_WITH_TYPE = True
 321
 322    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
 323    SUPPORTS_TABLE_COPY = True
 324
 325    # Whether parentheses are required around the table sample's expression
 326    TABLESAMPLE_REQUIRES_PARENS = True
 327
 328    # Whether a table sample clause's size needs to be followed by the ROWS keyword
 329    TABLESAMPLE_SIZE_IS_ROWS = True
 330
 331    # The keyword(s) to use when generating a sample clause
 332    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
 333
 334    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
 335    TABLESAMPLE_WITH_METHOD = True
 336
 337    # The keyword to use when specifying the seed of a sample clause
 338    TABLESAMPLE_SEED_KEYWORD = "SEED"
 339
 340    # Whether COLLATE is a function instead of a binary operator
 341    COLLATE_IS_FUNC = False
 342
 343    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
 344    DATA_TYPE_SPECIFIERS_ALLOWED = False
 345
 346    # Whether conditions require booleans WHERE x = 0 vs WHERE x
 347    ENSURE_BOOLS = False
 348
 349    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
 350    CTE_RECURSIVE_KEYWORD_REQUIRED = True
 351
 352    # Whether CONCAT requires >1 arguments
 353    SUPPORTS_SINGLE_ARG_CONCAT = True
 354
 355    # Whether LAST_DAY function supports a date part argument
 356    LAST_DAY_SUPPORTS_DATE_PART = True
 357
 358    # Whether named columns are allowed in table aliases
 359    SUPPORTS_TABLE_ALIAS_COLUMNS = True
 360
 361    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
 362    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
 363
 364    # What delimiter to use for separating JSON key/value pairs
 365    JSON_KEY_VALUE_PAIR_SEP = ":"
 366
 367    # INSERT OVERWRITE TABLE x override
 368    INSERT_OVERWRITE = " OVERWRITE TABLE"
 369
 370    # Whether the SELECT .. INTO syntax is used instead of CTAS
 371    SUPPORTS_SELECT_INTO = False
 372
 373    # Whether UNLOGGED tables can be created
 374    SUPPORTS_UNLOGGED_TABLES = False
 375
 376    # Whether the CREATE TABLE LIKE statement is supported
 377    SUPPORTS_CREATE_TABLE_LIKE = True
 378
 379    # Whether the LikeProperty needs to be specified inside of the schema clause
 380    LIKE_PROPERTY_INSIDE_SCHEMA = False
 381
 382    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
 383    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
 384    MULTI_ARG_DISTINCT = True
 385
 386    # Whether the JSON extraction operators expect a value of type JSON
 387    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
 388
 389    # Whether bracketed keys like ["foo"] are supported in JSON paths
 390    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
 391
 392    # Whether to escape keys using single quotes in JSON paths
 393    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
 394
 395    # The JSONPathPart expressions supported by this dialect
 396    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
 397
 398    # Whether any(f(x) for x in array) can be implemented by this dialect
 399    CAN_IMPLEMENT_ARRAY_ANY = False
 400
 401    # Whether the function TO_NUMBER is supported
 402    SUPPORTS_TO_NUMBER = True
 403
 404    # Whether or not set op modifiers apply to the outer set op or select.
 405    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
 406    # True means limit 1 happens after the set op, False means it it happens on y.
 407    SET_OP_MODIFIERS = True
 408
 409    # Whether parameters from COPY statement are wrapped in parentheses
 410    COPY_PARAMS_ARE_WRAPPED = True
 411
 412    # Whether values of params are set with "=" token or empty space
 413    COPY_PARAMS_EQ_REQUIRED = False
 414
 415    # Whether COPY statement has INTO keyword
 416    COPY_HAS_INTO_KEYWORD = True
 417
 418    # Whether the conditional TRY(expression) function is supported
 419    TRY_SUPPORTED = True
 420
 421    # Whether the UESCAPE syntax in unicode strings is supported
 422    SUPPORTS_UESCAPE = True
 423
 424    # The keyword to use when generating a star projection with excluded columns
 425    STAR_EXCEPT = "EXCEPT"
 426
 427    # The HEX function name
 428    HEX_FUNC = "HEX"
 429
 430    # The keywords to use when prefixing & separating WITH based properties
 431    WITH_PROPERTIES_PREFIX = "WITH"
 432
 433    # Whether to quote the generated expression of exp.JsonPath
 434    QUOTE_JSON_PATH = True
 435
 436    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
 437    PAD_FILL_PATTERN_IS_REQUIRED = False
 438
 439    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
 440    SUPPORTS_EXPLODING_PROJECTIONS = True
 441
 442    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
 443    ARRAY_CONCAT_IS_VAR_LEN = True
 444
 445    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
 446    SUPPORTS_CONVERT_TIMEZONE = False
 447
 448    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
 449    SUPPORTS_MEDIAN = True
 450
 451    # Whether UNIX_SECONDS(timestamp) is supported
 452    SUPPORTS_UNIX_SECONDS = False
 453
 454    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
 455    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
 456
 457    # The function name of the exp.ArraySize expression
 458    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
 459
 460    # The syntax to use when altering the type of a column
 461    ALTER_SET_TYPE = "SET DATA TYPE"
 462
 463    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
 464    # None -> Doesn't support it at all
 465    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
 466    # True (Postgres) -> Explicitly requires it
 467    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
 468
 469    TYPE_MAPPING = {
 470        exp.DataType.Type.DATETIME2: "TIMESTAMP",
 471        exp.DataType.Type.NCHAR: "CHAR",
 472        exp.DataType.Type.NVARCHAR: "VARCHAR",
 473        exp.DataType.Type.MEDIUMTEXT: "TEXT",
 474        exp.DataType.Type.LONGTEXT: "TEXT",
 475        exp.DataType.Type.TINYTEXT: "TEXT",
 476        exp.DataType.Type.BLOB: "VARBINARY",
 477        exp.DataType.Type.MEDIUMBLOB: "BLOB",
 478        exp.DataType.Type.LONGBLOB: "BLOB",
 479        exp.DataType.Type.TINYBLOB: "BLOB",
 480        exp.DataType.Type.INET: "INET",
 481        exp.DataType.Type.ROWVERSION: "VARBINARY",
 482        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
 483    }
 484
 485    TIME_PART_SINGULARS = {
 486        "MICROSECONDS": "MICROSECOND",
 487        "SECONDS": "SECOND",
 488        "MINUTES": "MINUTE",
 489        "HOURS": "HOUR",
 490        "DAYS": "DAY",
 491        "WEEKS": "WEEK",
 492        "MONTHS": "MONTH",
 493        "QUARTERS": "QUARTER",
 494        "YEARS": "YEAR",
 495    }
 496
 497    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 498        "cluster": lambda self, e: self.sql(e, "cluster"),
 499        "distribute": lambda self, e: self.sql(e, "distribute"),
 500        "sort": lambda self, e: self.sql(e, "sort"),
 501        "windows": lambda self, e: (
 502            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
 503            if e.args.get("windows")
 504            else ""
 505        ),
 506        "qualify": lambda self, e: self.sql(e, "qualify"),
 507    }
 508
 509    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
 510
 511    STRUCT_DELIMITER = ("<", ">")
 512
 513    PARAMETER_TOKEN = "@"
 514    NAMED_PLACEHOLDER_TOKEN = ":"
 515
 516    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
 517
 518    PROPERTIES_LOCATION = {
 519        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
 520        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
 521        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
 522        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
 523        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
 524        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
 525        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
 526        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
 527        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
 528        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
 529        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
 530        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
 531        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
 532        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
 533        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
 534        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
 535        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
 536        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
 537        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
 538        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
 539        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 540        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 541        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
 542        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
 543        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
 544        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
 545        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
 546        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
 547        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
 548        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
 549        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
 550        exp.HeapProperty: exp.Properties.Location.POST_WITH,
 551        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
 552        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
 553        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
 554        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
 555        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
 556        exp.JournalProperty: exp.Properties.Location.POST_NAME,
 557        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
 558        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
 559        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
 560        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
 561        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
 562        exp.LogProperty: exp.Properties.Location.POST_NAME,
 563        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
 564        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
 565        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
 566        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
 567        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
 568        exp.Order: exp.Properties.Location.POST_SCHEMA,
 569        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
 570        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
 571        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
 572        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
 573        exp.Property: exp.Properties.Location.POST_WITH,
 574        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
 575        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
 576        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
 577        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
 578        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
 579        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
 580        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
 581        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
 582        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
 583        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
 584        exp.Set: exp.Properties.Location.POST_SCHEMA,
 585        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
 586        exp.SetProperty: exp.Properties.Location.POST_CREATE,
 587        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
 588        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
 589        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
 590        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 591        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
 592        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
 593        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
 594        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
 595        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
 596        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
 597        exp.Tags: exp.Properties.Location.POST_WITH,
 598        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
 599        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
 600        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
 601        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
 602        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
 603        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
 604        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
 605        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
 606        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
 607        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
 608        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
 609        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
 610        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
 611        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
 612        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
 613    }
 614
 615    # Keywords that can't be used as unquoted identifier names
 616    RESERVED_KEYWORDS: t.Set[str] = set()
 617
 618    # Expressions whose comments are separated from them for better formatting
 619    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 620        exp.Command,
 621        exp.Create,
 622        exp.Describe,
 623        exp.Delete,
 624        exp.Drop,
 625        exp.From,
 626        exp.Insert,
 627        exp.Join,
 628        exp.MultitableInserts,
 629        exp.Select,
 630        exp.SetOperation,
 631        exp.Update,
 632        exp.Where,
 633        exp.With,
 634    )
 635
 636    # Expressions that should not have their comments generated in maybe_comment
 637    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 638        exp.Binary,
 639        exp.SetOperation,
 640    )
 641
 642    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
 643    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
 644        exp.Column,
 645        exp.Literal,
 646        exp.Neg,
 647        exp.Paren,
 648    )
 649
 650    PARAMETERIZABLE_TEXT_TYPES = {
 651        exp.DataType.Type.NVARCHAR,
 652        exp.DataType.Type.VARCHAR,
 653        exp.DataType.Type.CHAR,
 654        exp.DataType.Type.NCHAR,
 655    }
 656
 657    # Expressions that need to have all CTEs under them bubbled up to them
 658    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
 659
 660    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
 661
 662    __slots__ = (
 663        "pretty",
 664        "identify",
 665        "normalize",
 666        "pad",
 667        "_indent",
 668        "normalize_functions",
 669        "unsupported_level",
 670        "max_unsupported",
 671        "leading_comma",
 672        "max_text_width",
 673        "comments",
 674        "dialect",
 675        "unsupported_messages",
 676        "_escaped_quote_end",
 677        "_escaped_identifier_end",
 678        "_next_name",
 679        "_identifier_start",
 680        "_identifier_end",
 681        "_quote_json_path_key_using_brackets",
 682    )
 683
 684    def __init__(
 685        self,
 686        pretty: t.Optional[bool] = None,
 687        identify: str | bool = False,
 688        normalize: bool = False,
 689        pad: int = 2,
 690        indent: int = 2,
 691        normalize_functions: t.Optional[str | bool] = None,
 692        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 693        max_unsupported: int = 3,
 694        leading_comma: bool = False,
 695        max_text_width: int = 80,
 696        comments: bool = True,
 697        dialect: DialectType = None,
 698    ):
 699        import sqlglot
 700        from sqlglot.dialects import Dialect
 701
 702        self.pretty = pretty if pretty is not None else sqlglot.pretty
 703        self.identify = identify
 704        self.normalize = normalize
 705        self.pad = pad
 706        self._indent = indent
 707        self.unsupported_level = unsupported_level
 708        self.max_unsupported = max_unsupported
 709        self.leading_comma = leading_comma
 710        self.max_text_width = max_text_width
 711        self.comments = comments
 712        self.dialect = Dialect.get_or_raise(dialect)
 713
 714        # This is both a Dialect property and a Generator argument, so we prioritize the latter
 715        self.normalize_functions = (
 716            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
 717        )
 718
 719        self.unsupported_messages: t.List[str] = []
 720        self._escaped_quote_end: str = (
 721            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
 722        )
 723        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
 724
 725        self._next_name = name_sequence("_t")
 726
 727        self._identifier_start = self.dialect.IDENTIFIER_START
 728        self._identifier_end = self.dialect.IDENTIFIER_END
 729
 730        self._quote_json_path_key_using_brackets = True
 731
 732    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
 733        """
 734        Generates the SQL string corresponding to the given syntax tree.
 735
 736        Args:
 737            expression: The syntax tree.
 738            copy: Whether to copy the expression. The generator performs mutations so
 739                it is safer to copy.
 740
 741        Returns:
 742            The SQL string corresponding to `expression`.
 743        """
 744        if copy:
 745            expression = expression.copy()
 746
 747        expression = self.preprocess(expression)
 748
 749        self.unsupported_messages = []
 750        sql = self.sql(expression).strip()
 751
 752        if self.pretty:
 753            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
 754
 755        if self.unsupported_level == ErrorLevel.IGNORE:
 756            return sql
 757
 758        if self.unsupported_level == ErrorLevel.WARN:
 759            for msg in self.unsupported_messages:
 760                logger.warning(msg)
 761        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
 762            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
 763
 764        return sql
 765
 766    def preprocess(self, expression: exp.Expression) -> exp.Expression:
 767        """Apply generic preprocessing transformations to a given expression."""
 768        expression = self._move_ctes_to_top_level(expression)
 769
 770        if self.ENSURE_BOOLS:
 771            from sqlglot.transforms import ensure_bools
 772
 773            expression = ensure_bools(expression)
 774
 775        return expression
 776
 777    def _move_ctes_to_top_level(self, expression: E) -> E:
 778        if (
 779            not expression.parent
 780            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
 781            and any(node.parent is not expression for node in expression.find_all(exp.With))
 782        ):
 783            from sqlglot.transforms import move_ctes_to_top_level
 784
 785            expression = move_ctes_to_top_level(expression)
 786        return expression
 787
 788    def unsupported(self, message: str) -> None:
 789        if self.unsupported_level == ErrorLevel.IMMEDIATE:
 790            raise UnsupportedError(message)
 791        self.unsupported_messages.append(message)
 792
 793    def sep(self, sep: str = " ") -> str:
 794        return f"{sep.strip()}\n" if self.pretty else sep
 795
 796    def seg(self, sql: str, sep: str = " ") -> str:
 797        return f"{self.sep(sep)}{sql}"
 798
 799    def pad_comment(self, comment: str) -> str:
 800        comment = " " + comment if comment[0].strip() else comment
 801        comment = comment + " " if comment[-1].strip() else comment
 802        return comment
 803
 804    def maybe_comment(
 805        self,
 806        sql: str,
 807        expression: t.Optional[exp.Expression] = None,
 808        comments: t.Optional[t.List[str]] = None,
 809        separated: bool = False,
 810    ) -> str:
 811        comments = (
 812            ((expression and expression.comments) if comments is None else comments)  # type: ignore
 813            if self.comments
 814            else None
 815        )
 816
 817        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
 818            return sql
 819
 820        comments_sql = " ".join(
 821            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
 822        )
 823
 824        if not comments_sql:
 825            return sql
 826
 827        comments_sql = self._replace_line_breaks(comments_sql)
 828
 829        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
 830            return (
 831                f"{self.sep()}{comments_sql}{sql}"
 832                if not sql or sql[0].isspace()
 833                else f"{comments_sql}{self.sep()}{sql}"
 834            )
 835
 836        return f"{sql} {comments_sql}"
 837
 838    def wrap(self, expression: exp.Expression | str) -> str:
 839        this_sql = (
 840            self.sql(expression)
 841            if isinstance(expression, exp.UNWRAPPED_QUERIES)
 842            else self.sql(expression, "this")
 843        )
 844        if not this_sql:
 845            return "()"
 846
 847        this_sql = self.indent(this_sql, level=1, pad=0)
 848        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
 849
 850    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
 851        original = self.identify
 852        self.identify = False
 853        result = func(*args, **kwargs)
 854        self.identify = original
 855        return result
 856
 857    def normalize_func(self, name: str) -> str:
 858        if self.normalize_functions == "upper" or self.normalize_functions is True:
 859            return name.upper()
 860        if self.normalize_functions == "lower":
 861            return name.lower()
 862        return name
 863
 864    def indent(
 865        self,
 866        sql: str,
 867        level: int = 0,
 868        pad: t.Optional[int] = None,
 869        skip_first: bool = False,
 870        skip_last: bool = False,
 871    ) -> str:
 872        if not self.pretty or not sql:
 873            return sql
 874
 875        pad = self.pad if pad is None else pad
 876        lines = sql.split("\n")
 877
 878        return "\n".join(
 879            (
 880                line
 881                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
 882                else f"{' ' * (level * self._indent + pad)}{line}"
 883            )
 884            for i, line in enumerate(lines)
 885        )
 886
 887    def sql(
 888        self,
 889        expression: t.Optional[str | exp.Expression],
 890        key: t.Optional[str] = None,
 891        comment: bool = True,
 892    ) -> str:
 893        if not expression:
 894            return ""
 895
 896        if isinstance(expression, str):
 897            return expression
 898
 899        if key:
 900            value = expression.args.get(key)
 901            if value:
 902                return self.sql(value)
 903            return ""
 904
 905        transform = self.TRANSFORMS.get(expression.__class__)
 906
 907        if callable(transform):
 908            sql = transform(self, expression)
 909        elif isinstance(expression, exp.Expression):
 910            exp_handler_name = f"{expression.key}_sql"
 911
 912            if hasattr(self, exp_handler_name):
 913                sql = getattr(self, exp_handler_name)(expression)
 914            elif isinstance(expression, exp.Func):
 915                sql = self.function_fallback_sql(expression)
 916            elif isinstance(expression, exp.Property):
 917                sql = self.property_sql(expression)
 918            else:
 919                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
 920        else:
 921            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
 922
 923        return self.maybe_comment(sql, expression) if self.comments and comment else sql
 924
 925    def uncache_sql(self, expression: exp.Uncache) -> str:
 926        table = self.sql(expression, "this")
 927        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
 928        return f"UNCACHE TABLE{exists_sql} {table}"
 929
 930    def cache_sql(self, expression: exp.Cache) -> str:
 931        lazy = " LAZY" if expression.args.get("lazy") else ""
 932        table = self.sql(expression, "this")
 933        options = expression.args.get("options")
 934        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
 935        sql = self.sql(expression, "expression")
 936        sql = f" AS{self.sep()}{sql}" if sql else ""
 937        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
 938        return self.prepend_ctes(expression, sql)
 939
 940    def characterset_sql(self, expression: exp.CharacterSet) -> str:
 941        if isinstance(expression.parent, exp.Cast):
 942            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
 943        default = "DEFAULT " if expression.args.get("default") else ""
 944        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
 945
 946    def column_parts(self, expression: exp.Column) -> str:
 947        return ".".join(
 948            self.sql(part)
 949            for part in (
 950                expression.args.get("catalog"),
 951                expression.args.get("db"),
 952                expression.args.get("table"),
 953                expression.args.get("this"),
 954            )
 955            if part
 956        )
 957
 958    def column_sql(self, expression: exp.Column) -> str:
 959        join_mark = " (+)" if expression.args.get("join_mark") else ""
 960
 961        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
 962            join_mark = ""
 963            self.unsupported("Outer join syntax using the (+) operator is not supported.")
 964
 965        return f"{self.column_parts(expression)}{join_mark}"
 966
 967    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
 968        this = self.sql(expression, "this")
 969        this = f" {this}" if this else ""
 970        position = self.sql(expression, "position")
 971        return f"{position}{this}"
 972
 973    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
 974        column = self.sql(expression, "this")
 975        kind = self.sql(expression, "kind")
 976        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
 977        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
 978        kind = f"{sep}{kind}" if kind else ""
 979        constraints = f" {constraints}" if constraints else ""
 980        position = self.sql(expression, "position")
 981        position = f" {position}" if position else ""
 982
 983        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
 984            kind = ""
 985
 986        return f"{exists}{column}{kind}{constraints}{position}"
 987
 988    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
 989        this = self.sql(expression, "this")
 990        kind_sql = self.sql(expression, "kind").strip()
 991        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
 992
 993    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
 994        this = self.sql(expression, "this")
 995        if expression.args.get("not_null"):
 996            persisted = " PERSISTED NOT NULL"
 997        elif expression.args.get("persisted"):
 998            persisted = " PERSISTED"
 999        else:
1000            persisted = ""
1001        return f"AS {this}{persisted}"
1002
1003    def autoincrementcolumnconstraint_sql(self, _) -> str:
1004        return self.token_sql(TokenType.AUTO_INCREMENT)
1005
1006    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1007        if isinstance(expression.this, list):
1008            this = self.wrap(self.expressions(expression, key="this", flat=True))
1009        else:
1010            this = self.sql(expression, "this")
1011
1012        return f"COMPRESS {this}"
1013
1014    def generatedasidentitycolumnconstraint_sql(
1015        self, expression: exp.GeneratedAsIdentityColumnConstraint
1016    ) -> str:
1017        this = ""
1018        if expression.this is not None:
1019            on_null = " ON NULL" if expression.args.get("on_null") else ""
1020            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1021
1022        start = expression.args.get("start")
1023        start = f"START WITH {start}" if start else ""
1024        increment = expression.args.get("increment")
1025        increment = f" INCREMENT BY {increment}" if increment else ""
1026        minvalue = expression.args.get("minvalue")
1027        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1028        maxvalue = expression.args.get("maxvalue")
1029        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1030        cycle = expression.args.get("cycle")
1031        cycle_sql = ""
1032
1033        if cycle is not None:
1034            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1035            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1036
1037        sequence_opts = ""
1038        if start or increment or cycle_sql:
1039            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1040            sequence_opts = f" ({sequence_opts.strip()})"
1041
1042        expr = self.sql(expression, "expression")
1043        expr = f"({expr})" if expr else "IDENTITY"
1044
1045        return f"GENERATED{this} AS {expr}{sequence_opts}"
1046
1047    def generatedasrowcolumnconstraint_sql(
1048        self, expression: exp.GeneratedAsRowColumnConstraint
1049    ) -> str:
1050        start = "START" if expression.args.get("start") else "END"
1051        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1052        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
1053
1054    def periodforsystemtimeconstraint_sql(
1055        self, expression: exp.PeriodForSystemTimeConstraint
1056    ) -> str:
1057        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
1058
1059    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1060        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
1061
1062    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
1063        return f"AS {self.sql(expression, 'this')}"
1064
1065    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1066        desc = expression.args.get("desc")
1067        if desc is not None:
1068            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1069        options = self.expressions(expression, key="options", flat=True, sep=" ")
1070        options = f" {options}" if options else ""
1071        return f"PRIMARY KEY{options}"
1072
1073    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1074        this = self.sql(expression, "this")
1075        this = f" {this}" if this else ""
1076        index_type = expression.args.get("index_type")
1077        index_type = f" USING {index_type}" if index_type else ""
1078        on_conflict = self.sql(expression, "on_conflict")
1079        on_conflict = f" {on_conflict}" if on_conflict else ""
1080        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1081        options = self.expressions(expression, key="options", flat=True, sep=" ")
1082        options = f" {options}" if options else ""
1083        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
1084
1085    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1086        return self.sql(expression, "this")
1087
1088    def create_sql(self, expression: exp.Create) -> str:
1089        kind = self.sql(expression, "kind")
1090        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1091        properties = expression.args.get("properties")
1092        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1093
1094        this = self.createable_sql(expression, properties_locs)
1095
1096        properties_sql = ""
1097        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1098            exp.Properties.Location.POST_WITH
1099        ):
1100            properties_sql = self.sql(
1101                exp.Properties(
1102                    expressions=[
1103                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1104                        *properties_locs[exp.Properties.Location.POST_WITH],
1105                    ]
1106                )
1107            )
1108
1109            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1110                properties_sql = self.sep() + properties_sql
1111            elif not self.pretty:
1112                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1113                properties_sql = f" {properties_sql}"
1114
1115        begin = " BEGIN" if expression.args.get("begin") else ""
1116        end = " END" if expression.args.get("end") else ""
1117
1118        expression_sql = self.sql(expression, "expression")
1119        if expression_sql:
1120            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1121
1122            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1123                postalias_props_sql = ""
1124                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1125                    postalias_props_sql = self.properties(
1126                        exp.Properties(
1127                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1128                        ),
1129                        wrapped=False,
1130                    )
1131                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1132                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1133
1134        postindex_props_sql = ""
1135        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1136            postindex_props_sql = self.properties(
1137                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1138                wrapped=False,
1139                prefix=" ",
1140            )
1141
1142        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1143        indexes = f" {indexes}" if indexes else ""
1144        index_sql = indexes + postindex_props_sql
1145
1146        replace = " OR REPLACE" if expression.args.get("replace") else ""
1147        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1148        unique = " UNIQUE" if expression.args.get("unique") else ""
1149
1150        clustered = expression.args.get("clustered")
1151        if clustered is None:
1152            clustered_sql = ""
1153        elif clustered:
1154            clustered_sql = " CLUSTERED COLUMNSTORE"
1155        else:
1156            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1157
1158        postcreate_props_sql = ""
1159        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1160            postcreate_props_sql = self.properties(
1161                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1162                sep=" ",
1163                prefix=" ",
1164                wrapped=False,
1165            )
1166
1167        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1168
1169        postexpression_props_sql = ""
1170        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1171            postexpression_props_sql = self.properties(
1172                exp.Properties(
1173                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1174                ),
1175                sep=" ",
1176                prefix=" ",
1177                wrapped=False,
1178            )
1179
1180        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1181        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1182        no_schema_binding = (
1183            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1184        )
1185
1186        clone = self.sql(expression, "clone")
1187        clone = f" {clone}" if clone else ""
1188
1189        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1190            properties_expression = f"{expression_sql}{properties_sql}"
1191        else:
1192            properties_expression = f"{properties_sql}{expression_sql}"
1193
1194        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1195        return self.prepend_ctes(expression, expression_sql)
1196
1197    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1198        start = self.sql(expression, "start")
1199        start = f"START WITH {start}" if start else ""
1200        increment = self.sql(expression, "increment")
1201        increment = f" INCREMENT BY {increment}" if increment else ""
1202        minvalue = self.sql(expression, "minvalue")
1203        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1204        maxvalue = self.sql(expression, "maxvalue")
1205        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1206        owned = self.sql(expression, "owned")
1207        owned = f" OWNED BY {owned}" if owned else ""
1208
1209        cache = expression.args.get("cache")
1210        if cache is None:
1211            cache_str = ""
1212        elif cache is True:
1213            cache_str = " CACHE"
1214        else:
1215            cache_str = f" CACHE {cache}"
1216
1217        options = self.expressions(expression, key="options", flat=True, sep=" ")
1218        options = f" {options}" if options else ""
1219
1220        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1221
1222    def clone_sql(self, expression: exp.Clone) -> str:
1223        this = self.sql(expression, "this")
1224        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1225        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1226        return f"{shallow}{keyword} {this}"
1227
1228    def describe_sql(self, expression: exp.Describe) -> str:
1229        style = expression.args.get("style")
1230        style = f" {style}" if style else ""
1231        partition = self.sql(expression, "partition")
1232        partition = f" {partition}" if partition else ""
1233        format = self.sql(expression, "format")
1234        format = f" {format}" if format else ""
1235
1236        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1237
1238    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1239        tag = self.sql(expression, "tag")
1240        return f"${tag}${self.sql(expression, 'this')}${tag}$"
1241
1242    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1243        with_ = self.sql(expression, "with")
1244        if with_:
1245            sql = f"{with_}{self.sep()}{sql}"
1246        return sql
1247
1248    def with_sql(self, expression: exp.With) -> str:
1249        sql = self.expressions(expression, flat=True)
1250        recursive = (
1251            "RECURSIVE "
1252            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1253            else ""
1254        )
1255        search = self.sql(expression, "search")
1256        search = f" {search}" if search else ""
1257
1258        return f"WITH {recursive}{sql}{search}"
1259
1260    def cte_sql(self, expression: exp.CTE) -> str:
1261        alias = expression.args.get("alias")
1262        if alias:
1263            alias.add_comments(expression.pop_comments())
1264
1265        alias_sql = self.sql(expression, "alias")
1266
1267        materialized = expression.args.get("materialized")
1268        if materialized is False:
1269            materialized = "NOT MATERIALIZED "
1270        elif materialized:
1271            materialized = "MATERIALIZED "
1272
1273        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1274
1275    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1276        alias = self.sql(expression, "this")
1277        columns = self.expressions(expression, key="columns", flat=True)
1278        columns = f"({columns})" if columns else ""
1279
1280        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1281            columns = ""
1282            self.unsupported("Named columns are not supported in table alias.")
1283
1284        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1285            alias = self._next_name()
1286
1287        return f"{alias}{columns}"
1288
1289    def bitstring_sql(self, expression: exp.BitString) -> str:
1290        this = self.sql(expression, "this")
1291        if self.dialect.BIT_START:
1292            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1293        return f"{int(this, 2)}"
1294
1295    def hexstring_sql(
1296        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1297    ) -> str:
1298        this = self.sql(expression, "this")
1299        is_integer_type = expression.args.get("is_integer")
1300
1301        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1302            not self.dialect.HEX_START and not binary_function_repr
1303        ):
1304            # Integer representation will be returned if:
1305            # - The read dialect treats the hex value as integer literal but not the write
1306            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1307            return f"{int(this, 16)}"
1308
1309        if not is_integer_type:
1310            # Read dialect treats the hex value as BINARY/BLOB
1311            if binary_function_repr:
1312                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1313                return self.func(binary_function_repr, exp.Literal.string(this))
1314            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1315                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1316                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1317
1318        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1319
1320    def bytestring_sql(self, expression: exp.ByteString) -> str:
1321        this = self.sql(expression, "this")
1322        if self.dialect.BYTE_START:
1323            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1324        return this
1325
1326    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1327        this = self.sql(expression, "this")
1328        escape = expression.args.get("escape")
1329
1330        if self.dialect.UNICODE_START:
1331            escape_substitute = r"\\\1"
1332            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1333        else:
1334            escape_substitute = r"\\u\1"
1335            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1336
1337        if escape:
1338            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1339            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1340        else:
1341            escape_pattern = ESCAPED_UNICODE_RE
1342            escape_sql = ""
1343
1344        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1345            this = escape_pattern.sub(escape_substitute, this)
1346
1347        return f"{left_quote}{this}{right_quote}{escape_sql}"
1348
1349    def rawstring_sql(self, expression: exp.RawString) -> str:
1350        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
1351        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
1352
1353    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1354        this = self.sql(expression, "this")
1355        specifier = self.sql(expression, "expression")
1356        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1357        return f"{this}{specifier}"
1358
1359    def datatype_sql(self, expression: exp.DataType) -> str:
1360        nested = ""
1361        values = ""
1362        interior = self.expressions(expression, flat=True)
1363
1364        type_value = expression.this
1365        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1366            type_sql = self.sql(expression, "kind")
1367        else:
1368            type_sql = (
1369                self.TYPE_MAPPING.get(type_value, type_value.value)
1370                if isinstance(type_value, exp.DataType.Type)
1371                else type_value
1372            )
1373
1374        if interior:
1375            if expression.args.get("nested"):
1376                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1377                if expression.args.get("values") is not None:
1378                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1379                    values = self.expressions(expression, key="values", flat=True)
1380                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1381            elif type_value == exp.DataType.Type.INTERVAL:
1382                nested = f" {interior}"
1383            else:
1384                nested = f"({interior})"
1385
1386        type_sql = f"{type_sql}{nested}{values}"
1387        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1388            exp.DataType.Type.TIMETZ,
1389            exp.DataType.Type.TIMESTAMPTZ,
1390        ):
1391            type_sql = f"{type_sql} WITH TIME ZONE"
1392
1393        return type_sql
1394
1395    def directory_sql(self, expression: exp.Directory) -> str:
1396        local = "LOCAL " if expression.args.get("local") else ""
1397        row_format = self.sql(expression, "row_format")
1398        row_format = f" {row_format}" if row_format else ""
1399        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1400
1401    def delete_sql(self, expression: exp.Delete) -> str:
1402        this = self.sql(expression, "this")
1403        this = f" FROM {this}" if this else ""
1404        using = self.sql(expression, "using")
1405        using = f" USING {using}" if using else ""
1406        cluster = self.sql(expression, "cluster")
1407        cluster = f" {cluster}" if cluster else ""
1408        where = self.sql(expression, "where")
1409        returning = self.sql(expression, "returning")
1410        limit = self.sql(expression, "limit")
1411        tables = self.expressions(expression, key="tables")
1412        tables = f" {tables}" if tables else ""
1413        if self.RETURNING_END:
1414            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1415        else:
1416            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1417        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1418
1419    def drop_sql(self, expression: exp.Drop) -> str:
1420        this = self.sql(expression, "this")
1421        expressions = self.expressions(expression, flat=True)
1422        expressions = f" ({expressions})" if expressions else ""
1423        kind = expression.args["kind"]
1424        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1425        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1426        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1427        on_cluster = self.sql(expression, "cluster")
1428        on_cluster = f" {on_cluster}" if on_cluster else ""
1429        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1430        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1431        cascade = " CASCADE" if expression.args.get("cascade") else ""
1432        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1433        purge = " PURGE" if expression.args.get("purge") else ""
1434        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1435
1436    def set_operation(self, expression: exp.SetOperation) -> str:
1437        op_type = type(expression)
1438        op_name = op_type.key.upper()
1439
1440        distinct = expression.args.get("distinct")
1441        if (
1442            distinct is False
1443            and op_type in (exp.Except, exp.Intersect)
1444            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1445        ):
1446            self.unsupported(f"{op_name} ALL is not supported")
1447
1448        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1449
1450        if distinct is None:
1451            distinct = default_distinct
1452            if distinct is None:
1453                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1454
1455        if distinct is default_distinct:
1456            distinct_or_all = ""
1457        else:
1458            distinct_or_all = " DISTINCT" if distinct else " ALL"
1459
1460        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1461        side_kind = f"{side_kind} " if side_kind else ""
1462
1463        by_name = " BY NAME" if expression.args.get("by_name") else ""
1464        on = self.expressions(expression, key="on", flat=True)
1465        on = f" ON ({on})" if on else ""
1466
1467        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
1468
1469    def set_operations(self, expression: exp.SetOperation) -> str:
1470        if not self.SET_OP_MODIFIERS:
1471            limit = expression.args.get("limit")
1472            order = expression.args.get("order")
1473
1474            if limit or order:
1475                select = self._move_ctes_to_top_level(
1476                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1477                )
1478
1479                if limit:
1480                    select = select.limit(limit.pop(), copy=False)
1481                if order:
1482                    select = select.order_by(order.pop(), copy=False)
1483                return self.sql(select)
1484
1485        sqls: t.List[str] = []
1486        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1487
1488        while stack:
1489            node = stack.pop()
1490
1491            if isinstance(node, exp.SetOperation):
1492                stack.append(node.expression)
1493                stack.append(
1494                    self.maybe_comment(
1495                        self.set_operation(node), comments=node.comments, separated=True
1496                    )
1497                )
1498                stack.append(node.this)
1499            else:
1500                sqls.append(self.sql(node))
1501
1502        this = self.sep().join(sqls)
1503        this = self.query_modifiers(expression, this)
1504        return self.prepend_ctes(expression, this)
1505
1506    def fetch_sql(self, expression: exp.Fetch) -> str:
1507        direction = expression.args.get("direction")
1508        direction = f" {direction}" if direction else ""
1509        count = self.sql(expression, "count")
1510        count = f" {count}" if count else ""
1511        limit_options = self.sql(expression, "limit_options")
1512        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1513        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1514
1515    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1516        percent = " PERCENT" if expression.args.get("percent") else ""
1517        rows = " ROWS" if expression.args.get("rows") else ""
1518        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1519        if not with_ties and rows:
1520            with_ties = " ONLY"
1521        return f"{percent}{rows}{with_ties}"
1522
1523    def filter_sql(self, expression: exp.Filter) -> str:
1524        if self.AGGREGATE_FILTER_SUPPORTED:
1525            this = self.sql(expression, "this")
1526            where = self.sql(expression, "expression").strip()
1527            return f"{this} FILTER({where})"
1528
1529        agg = expression.this
1530        agg_arg = agg.this
1531        cond = expression.expression.this
1532        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1533        return self.sql(agg)
1534
1535    def hint_sql(self, expression: exp.Hint) -> str:
1536        if not self.QUERY_HINTS:
1537            self.unsupported("Hints are not supported")
1538            return ""
1539
1540        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
1541
1542    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1543        using = self.sql(expression, "using")
1544        using = f" USING {using}" if using else ""
1545        columns = self.expressions(expression, key="columns", flat=True)
1546        columns = f"({columns})" if columns else ""
1547        partition_by = self.expressions(expression, key="partition_by", flat=True)
1548        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1549        where = self.sql(expression, "where")
1550        include = self.expressions(expression, key="include", flat=True)
1551        if include:
1552            include = f" INCLUDE ({include})"
1553        with_storage = self.expressions(expression, key="with_storage", flat=True)
1554        with_storage = f" WITH ({with_storage})" if with_storage else ""
1555        tablespace = self.sql(expression, "tablespace")
1556        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1557        on = self.sql(expression, "on")
1558        on = f" ON {on}" if on else ""
1559
1560        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1561
1562    def index_sql(self, expression: exp.Index) -> str:
1563        unique = "UNIQUE " if expression.args.get("unique") else ""
1564        primary = "PRIMARY " if expression.args.get("primary") else ""
1565        amp = "AMP " if expression.args.get("amp") else ""
1566        name = self.sql(expression, "this")
1567        name = f"{name} " if name else ""
1568        table = self.sql(expression, "table")
1569        table = f"{self.INDEX_ON} {table}" if table else ""
1570
1571        index = "INDEX " if not table else ""
1572
1573        params = self.sql(expression, "params")
1574        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1575
1576    def identifier_sql(self, expression: exp.Identifier) -> str:
1577        text = expression.name
1578        lower = text.lower()
1579        text = lower if self.normalize and not expression.quoted else text
1580        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1581        if (
1582            expression.quoted
1583            or self.dialect.can_identify(text, self.identify)
1584            or lower in self.RESERVED_KEYWORDS
1585            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1586        ):
1587            text = f"{self._identifier_start}{text}{self._identifier_end}"
1588        return text
1589
1590    def hex_sql(self, expression: exp.Hex) -> str:
1591        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1592        if self.dialect.HEX_LOWERCASE:
1593            text = self.func("LOWER", text)
1594
1595        return text
1596
1597    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1598        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1599        if not self.dialect.HEX_LOWERCASE:
1600            text = self.func("LOWER", text)
1601        return text
1602
1603    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1604        input_format = self.sql(expression, "input_format")
1605        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1606        output_format = self.sql(expression, "output_format")
1607        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1608        return self.sep().join((input_format, output_format))
1609
1610    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1611        string = self.sql(exp.Literal.string(expression.name))
1612        return f"{prefix}{string}"
1613
1614    def partition_sql(self, expression: exp.Partition) -> str:
1615        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1616        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
1617
1618    def properties_sql(self, expression: exp.Properties) -> str:
1619        root_properties = []
1620        with_properties = []
1621
1622        for p in expression.expressions:
1623            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1624            if p_loc == exp.Properties.Location.POST_WITH:
1625                with_properties.append(p)
1626            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1627                root_properties.append(p)
1628
1629        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1630        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1631
1632        if root_props and with_props and not self.pretty:
1633            with_props = " " + with_props
1634
1635        return root_props + with_props
1636
1637    def root_properties(self, properties: exp.Properties) -> str:
1638        if properties.expressions:
1639            return self.expressions(properties, indent=False, sep=" ")
1640        return ""
1641
1642    def properties(
1643        self,
1644        properties: exp.Properties,
1645        prefix: str = "",
1646        sep: str = ", ",
1647        suffix: str = "",
1648        wrapped: bool = True,
1649    ) -> str:
1650        if properties.expressions:
1651            expressions = self.expressions(properties, sep=sep, indent=False)
1652            if expressions:
1653                expressions = self.wrap(expressions) if wrapped else expressions
1654                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1655        return ""
1656
1657    def with_properties(self, properties: exp.Properties) -> str:
1658        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
1659
1660    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1661        properties_locs = defaultdict(list)
1662        for p in properties.expressions:
1663            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1664            if p_loc != exp.Properties.Location.UNSUPPORTED:
1665                properties_locs[p_loc].append(p)
1666            else:
1667                self.unsupported(f"Unsupported property {p.key}")
1668
1669        return properties_locs
1670
1671    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1672        if isinstance(expression.this, exp.Dot):
1673            return self.sql(expression, "this")
1674        return f"'{expression.name}'" if string_key else expression.name
1675
1676    def property_sql(self, expression: exp.Property) -> str:
1677        property_cls = expression.__class__
1678        if property_cls == exp.Property:
1679            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1680
1681        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1682        if not property_name:
1683            self.unsupported(f"Unsupported property {expression.key}")
1684
1685        return f"{property_name}={self.sql(expression, 'this')}"
1686
1687    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1688        if self.SUPPORTS_CREATE_TABLE_LIKE:
1689            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1690            options = f" {options}" if options else ""
1691
1692            like = f"LIKE {self.sql(expression, 'this')}{options}"
1693            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1694                like = f"({like})"
1695
1696            return like
1697
1698        if expression.expressions:
1699            self.unsupported("Transpilation of LIKE property options is unsupported")
1700
1701        select = exp.select("*").from_(expression.this).limit(0)
1702        return f"AS {self.sql(select)}"
1703
1704    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1705        no = "NO " if expression.args.get("no") else ""
1706        protection = " PROTECTION" if expression.args.get("protection") else ""
1707        return f"{no}FALLBACK{protection}"
1708
1709    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1710        no = "NO " if expression.args.get("no") else ""
1711        local = expression.args.get("local")
1712        local = f"{local} " if local else ""
1713        dual = "DUAL " if expression.args.get("dual") else ""
1714        before = "BEFORE " if expression.args.get("before") else ""
1715        after = "AFTER " if expression.args.get("after") else ""
1716        return f"{no}{local}{dual}{before}{after}JOURNAL"
1717
1718    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1719        freespace = self.sql(expression, "this")
1720        percent = " PERCENT" if expression.args.get("percent") else ""
1721        return f"FREESPACE={freespace}{percent}"
1722
1723    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1724        if expression.args.get("default"):
1725            property = "DEFAULT"
1726        elif expression.args.get("on"):
1727            property = "ON"
1728        else:
1729            property = "OFF"
1730        return f"CHECKSUM={property}"
1731
1732    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1733        if expression.args.get("no"):
1734            return "NO MERGEBLOCKRATIO"
1735        if expression.args.get("default"):
1736            return "DEFAULT MERGEBLOCKRATIO"
1737
1738        percent = " PERCENT" if expression.args.get("percent") else ""
1739        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1740
1741    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1742        default = expression.args.get("default")
1743        minimum = expression.args.get("minimum")
1744        maximum = expression.args.get("maximum")
1745        if default or minimum or maximum:
1746            if default:
1747                prop = "DEFAULT"
1748            elif minimum:
1749                prop = "MINIMUM"
1750            else:
1751                prop = "MAXIMUM"
1752            return f"{prop} DATABLOCKSIZE"
1753        units = expression.args.get("units")
1754        units = f" {units}" if units else ""
1755        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
1756
1757    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1758        autotemp = expression.args.get("autotemp")
1759        always = expression.args.get("always")
1760        default = expression.args.get("default")
1761        manual = expression.args.get("manual")
1762        never = expression.args.get("never")
1763
1764        if autotemp is not None:
1765            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1766        elif always:
1767            prop = "ALWAYS"
1768        elif default:
1769            prop = "DEFAULT"
1770        elif manual:
1771            prop = "MANUAL"
1772        elif never:
1773            prop = "NEVER"
1774        return f"BLOCKCOMPRESSION={prop}"
1775
1776    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1777        no = expression.args.get("no")
1778        no = " NO" if no else ""
1779        concurrent = expression.args.get("concurrent")
1780        concurrent = " CONCURRENT" if concurrent else ""
1781        target = self.sql(expression, "target")
1782        target = f" {target}" if target else ""
1783        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1784
1785    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1786        if isinstance(expression.this, list):
1787            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1788        if expression.this:
1789            modulus = self.sql(expression, "this")
1790            remainder = self.sql(expression, "expression")
1791            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1792
1793        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1794        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1795        return f"FROM ({from_expressions}) TO ({to_expressions})"
1796
1797    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1798        this = self.sql(expression, "this")
1799
1800        for_values_or_default = expression.expression
1801        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1802            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1803        else:
1804            for_values_or_default = " DEFAULT"
1805
1806        return f"PARTITION OF {this}{for_values_or_default}"
1807
1808    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1809        kind = expression.args.get("kind")
1810        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1811        for_or_in = expression.args.get("for_or_in")
1812        for_or_in = f" {for_or_in}" if for_or_in else ""
1813        lock_type = expression.args.get("lock_type")
1814        override = " OVERRIDE" if expression.args.get("override") else ""
1815        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1816
1817    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1818        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1819        statistics = expression.args.get("statistics")
1820        statistics_sql = ""
1821        if statistics is not None:
1822            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1823        return f"{data_sql}{statistics_sql}"
1824
1825    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1826        this = self.sql(expression, "this")
1827        this = f"HISTORY_TABLE={this}" if this else ""
1828        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1829        data_consistency = (
1830            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1831        )
1832        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1833        retention_period = (
1834            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1835        )
1836
1837        if this:
1838            on_sql = self.func("ON", this, data_consistency, retention_period)
1839        else:
1840            on_sql = "ON" if expression.args.get("on") else "OFF"
1841
1842        sql = f"SYSTEM_VERSIONING={on_sql}"
1843
1844        return f"WITH({sql})" if expression.args.get("with") else sql
1845
1846    def insert_sql(self, expression: exp.Insert) -> str:
1847        hint = self.sql(expression, "hint")
1848        overwrite = expression.args.get("overwrite")
1849
1850        if isinstance(expression.this, exp.Directory):
1851            this = " OVERWRITE" if overwrite else " INTO"
1852        else:
1853            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1854
1855        stored = self.sql(expression, "stored")
1856        stored = f" {stored}" if stored else ""
1857        alternative = expression.args.get("alternative")
1858        alternative = f" OR {alternative}" if alternative else ""
1859        ignore = " IGNORE" if expression.args.get("ignore") else ""
1860        is_function = expression.args.get("is_function")
1861        if is_function:
1862            this = f"{this} FUNCTION"
1863        this = f"{this} {self.sql(expression, 'this')}"
1864
1865        exists = " IF EXISTS" if expression.args.get("exists") else ""
1866        where = self.sql(expression, "where")
1867        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1868        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1869        on_conflict = self.sql(expression, "conflict")
1870        on_conflict = f" {on_conflict}" if on_conflict else ""
1871        by_name = " BY NAME" if expression.args.get("by_name") else ""
1872        returning = self.sql(expression, "returning")
1873
1874        if self.RETURNING_END:
1875            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1876        else:
1877            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1878
1879        partition_by = self.sql(expression, "partition")
1880        partition_by = f" {partition_by}" if partition_by else ""
1881        settings = self.sql(expression, "settings")
1882        settings = f" {settings}" if settings else ""
1883
1884        source = self.sql(expression, "source")
1885        source = f"TABLE {source}" if source else ""
1886
1887        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1888        return self.prepend_ctes(expression, sql)
1889
1890    def introducer_sql(self, expression: exp.Introducer) -> str:
1891        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
1892
1893    def kill_sql(self, expression: exp.Kill) -> str:
1894        kind = self.sql(expression, "kind")
1895        kind = f" {kind}" if kind else ""
1896        this = self.sql(expression, "this")
1897        this = f" {this}" if this else ""
1898        return f"KILL{kind}{this}"
1899
1900    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1901        return expression.name
1902
1903    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1904        return expression.name
1905
1906    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1907        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1908
1909        constraint = self.sql(expression, "constraint")
1910        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1911
1912        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1913        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1914        action = self.sql(expression, "action")
1915
1916        expressions = self.expressions(expression, flat=True)
1917        if expressions:
1918            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1919            expressions = f" {set_keyword}{expressions}"
1920
1921        where = self.sql(expression, "where")
1922        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
1923
1924    def returning_sql(self, expression: exp.Returning) -> str:
1925        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
1926
1927    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1928        fields = self.sql(expression, "fields")
1929        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1930        escaped = self.sql(expression, "escaped")
1931        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1932        items = self.sql(expression, "collection_items")
1933        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1934        keys = self.sql(expression, "map_keys")
1935        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1936        lines = self.sql(expression, "lines")
1937        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1938        null = self.sql(expression, "null")
1939        null = f" NULL DEFINED AS {null}" if null else ""
1940        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1941
1942    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1943        return f"WITH ({self.expressions(expression, flat=True)})"
1944
1945    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1946        this = f"{self.sql(expression, 'this')} INDEX"
1947        target = self.sql(expression, "target")
1948        target = f" FOR {target}" if target else ""
1949        return f"{this}{target} ({self.expressions(expression, flat=True)})"
1950
1951    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1952        this = self.sql(expression, "this")
1953        kind = self.sql(expression, "kind")
1954        expr = self.sql(expression, "expression")
1955        return f"{this} ({kind} => {expr})"
1956
1957    def table_parts(self, expression: exp.Table) -> str:
1958        return ".".join(
1959            self.sql(part)
1960            for part in (
1961                expression.args.get("catalog"),
1962                expression.args.get("db"),
1963                expression.args.get("this"),
1964            )
1965            if part is not None
1966        )
1967
1968    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1969        table = self.table_parts(expression)
1970        only = "ONLY " if expression.args.get("only") else ""
1971        partition = self.sql(expression, "partition")
1972        partition = f" {partition}" if partition else ""
1973        version = self.sql(expression, "version")
1974        version = f" {version}" if version else ""
1975        alias = self.sql(expression, "alias")
1976        alias = f"{sep}{alias}" if alias else ""
1977
1978        sample = self.sql(expression, "sample")
1979        if self.dialect.ALIAS_POST_TABLESAMPLE:
1980            sample_pre_alias = sample
1981            sample_post_alias = ""
1982        else:
1983            sample_pre_alias = ""
1984            sample_post_alias = sample
1985
1986        hints = self.expressions(expression, key="hints", sep=" ")
1987        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
1988        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
1989        joins = self.indent(
1990            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
1991        )
1992        laterals = self.expressions(expression, key="laterals", sep="")
1993
1994        file_format = self.sql(expression, "format")
1995        if file_format:
1996            pattern = self.sql(expression, "pattern")
1997            pattern = f", PATTERN => {pattern}" if pattern else ""
1998            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
1999
2000        ordinality = expression.args.get("ordinality") or ""
2001        if ordinality:
2002            ordinality = f" WITH ORDINALITY{alias}"
2003            alias = ""
2004
2005        when = self.sql(expression, "when")
2006        if when:
2007            table = f"{table} {when}"
2008
2009        changes = self.sql(expression, "changes")
2010        changes = f" {changes}" if changes else ""
2011
2012        rows_from = self.expressions(expression, key="rows_from")
2013        if rows_from:
2014            table = f"ROWS FROM {self.wrap(rows_from)}"
2015
2016        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2017
2018    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2019        table = self.func("TABLE", expression.this)
2020        alias = self.sql(expression, "alias")
2021        alias = f" AS {alias}" if alias else ""
2022        sample = self.sql(expression, "sample")
2023        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2024        joins = self.indent(
2025            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2026        )
2027        return f"{table}{alias}{pivots}{sample}{joins}"
2028
2029    def tablesample_sql(
2030        self,
2031        expression: exp.TableSample,
2032        tablesample_keyword: t.Optional[str] = None,
2033    ) -> str:
2034        method = self.sql(expression, "method")
2035        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2036        numerator = self.sql(expression, "bucket_numerator")
2037        denominator = self.sql(expression, "bucket_denominator")
2038        field = self.sql(expression, "bucket_field")
2039        field = f" ON {field}" if field else ""
2040        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2041        seed = self.sql(expression, "seed")
2042        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2043
2044        size = self.sql(expression, "size")
2045        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2046            size = f"{size} ROWS"
2047
2048        percent = self.sql(expression, "percent")
2049        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2050            percent = f"{percent} PERCENT"
2051
2052        expr = f"{bucket}{percent}{size}"
2053        if self.TABLESAMPLE_REQUIRES_PARENS:
2054            expr = f"({expr})"
2055
2056        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2057
2058    def pivot_sql(self, expression: exp.Pivot) -> str:
2059        expressions = self.expressions(expression, flat=True)
2060        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2061
2062        group = self.sql(expression, "group")
2063
2064        if expression.this:
2065            this = self.sql(expression, "this")
2066            if not expressions:
2067                return f"UNPIVOT {this}"
2068
2069            on = f"{self.seg('ON')} {expressions}"
2070            into = self.sql(expression, "into")
2071            into = f"{self.seg('INTO')} {into}" if into else ""
2072            using = self.expressions(expression, key="using", flat=True)
2073            using = f"{self.seg('USING')} {using}" if using else ""
2074            return f"{direction} {this}{on}{into}{using}{group}"
2075
2076        alias = self.sql(expression, "alias")
2077        alias = f" AS {alias}" if alias else ""
2078
2079        fields = self.expressions(
2080            expression,
2081            "fields",
2082            sep=" ",
2083            dynamic=True,
2084            new_line=True,
2085            skip_first=True,
2086            skip_last=True,
2087        )
2088
2089        include_nulls = expression.args.get("include_nulls")
2090        if include_nulls is not None:
2091            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2092        else:
2093            nulls = ""
2094
2095        default_on_null = self.sql(expression, "default_on_null")
2096        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2097        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
2098
2099    def version_sql(self, expression: exp.Version) -> str:
2100        this = f"FOR {expression.name}"
2101        kind = expression.text("kind")
2102        expr = self.sql(expression, "expression")
2103        return f"{this} {kind} {expr}"
2104
2105    def tuple_sql(self, expression: exp.Tuple) -> str:
2106        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
2107
2108    def update_sql(self, expression: exp.Update) -> str:
2109        this = self.sql(expression, "this")
2110        set_sql = self.expressions(expression, flat=True)
2111        from_sql = self.sql(expression, "from")
2112        where_sql = self.sql(expression, "where")
2113        returning = self.sql(expression, "returning")
2114        order = self.sql(expression, "order")
2115        limit = self.sql(expression, "limit")
2116        if self.RETURNING_END:
2117            expression_sql = f"{from_sql}{where_sql}{returning}"
2118        else:
2119            expression_sql = f"{returning}{from_sql}{where_sql}"
2120        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2121        return self.prepend_ctes(expression, sql)
2122
2123    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2124        values_as_table = values_as_table and self.VALUES_AS_TABLE
2125
2126        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2127        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2128            args = self.expressions(expression)
2129            alias = self.sql(expression, "alias")
2130            values = f"VALUES{self.seg('')}{args}"
2131            values = (
2132                f"({values})"
2133                if self.WRAP_DERIVED_VALUES
2134                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2135                else values
2136            )
2137            return f"{values} AS {alias}" if alias else values
2138
2139        # Converts `VALUES...` expression into a series of select unions.
2140        alias_node = expression.args.get("alias")
2141        column_names = alias_node and alias_node.columns
2142
2143        selects: t.List[exp.Query] = []
2144
2145        for i, tup in enumerate(expression.expressions):
2146            row = tup.expressions
2147
2148            if i == 0 and column_names:
2149                row = [
2150                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2151                ]
2152
2153            selects.append(exp.Select(expressions=row))
2154
2155        if self.pretty:
2156            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2157            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2158            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2159            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2160            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2161
2162        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2163        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2164        return f"({unions}){alias}"
2165
2166    def var_sql(self, expression: exp.Var) -> str:
2167        return self.sql(expression, "this")
2168
2169    @unsupported_args("expressions")
2170    def into_sql(self, expression: exp.Into) -> str:
2171        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2172        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2173        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2174
2175    def from_sql(self, expression: exp.From) -> str:
2176        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
2177
2178    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2179        grouping_sets = self.expressions(expression, indent=False)
2180        return f"GROUPING SETS {self.wrap(grouping_sets)}"
2181
2182    def rollup_sql(self, expression: exp.Rollup) -> str:
2183        expressions = self.expressions(expression, indent=False)
2184        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
2185
2186    def cube_sql(self, expression: exp.Cube) -> str:
2187        expressions = self.expressions(expression, indent=False)
2188        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
2189
2190    def group_sql(self, expression: exp.Group) -> str:
2191        group_by_all = expression.args.get("all")
2192        if group_by_all is True:
2193            modifier = " ALL"
2194        elif group_by_all is False:
2195            modifier = " DISTINCT"
2196        else:
2197            modifier = ""
2198
2199        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2200
2201        grouping_sets = self.expressions(expression, key="grouping_sets")
2202        cube = self.expressions(expression, key="cube")
2203        rollup = self.expressions(expression, key="rollup")
2204
2205        groupings = csv(
2206            self.seg(grouping_sets) if grouping_sets else "",
2207            self.seg(cube) if cube else "",
2208            self.seg(rollup) if rollup else "",
2209            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2210            sep=self.GROUPINGS_SEP,
2211        )
2212
2213        if (
2214            expression.expressions
2215            and groupings
2216            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2217        ):
2218            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2219
2220        return f"{group_by}{groupings}"
2221
2222    def having_sql(self, expression: exp.Having) -> str:
2223        this = self.indent(self.sql(expression, "this"))
2224        return f"{self.seg('HAVING')}{self.sep()}{this}"
2225
2226    def connect_sql(self, expression: exp.Connect) -> str:
2227        start = self.sql(expression, "start")
2228        start = self.seg(f"START WITH {start}") if start else ""
2229        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2230        connect = self.sql(expression, "connect")
2231        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2232        return start + connect
2233
2234    def prior_sql(self, expression: exp.Prior) -> str:
2235        return f"PRIOR {self.sql(expression, 'this')}"
2236
2237    def join_sql(self, expression: exp.Join) -> str:
2238        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2239            side = None
2240        else:
2241            side = expression.side
2242
2243        op_sql = " ".join(
2244            op
2245            for op in (
2246                expression.method,
2247                "GLOBAL" if expression.args.get("global") else None,
2248                side,
2249                expression.kind,
2250                expression.hint if self.JOIN_HINTS else None,
2251            )
2252            if op
2253        )
2254        match_cond = self.sql(expression, "match_condition")
2255        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2256        on_sql = self.sql(expression, "on")
2257        using = expression.args.get("using")
2258
2259        if not on_sql and using:
2260            on_sql = csv(*(self.sql(column) for column in using))
2261
2262        this = expression.this
2263        this_sql = self.sql(this)
2264
2265        exprs = self.expressions(expression)
2266        if exprs:
2267            this_sql = f"{this_sql},{self.seg(exprs)}"
2268
2269        if on_sql:
2270            on_sql = self.indent(on_sql, skip_first=True)
2271            space = self.seg(" " * self.pad) if self.pretty else " "
2272            if using:
2273                on_sql = f"{space}USING ({on_sql})"
2274            else:
2275                on_sql = f"{space}ON {on_sql}"
2276        elif not op_sql:
2277            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2278                return f" {this_sql}"
2279
2280            return f", {this_sql}"
2281
2282        if op_sql != "STRAIGHT_JOIN":
2283            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2284
2285        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2286
2287    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2288        args = self.expressions(expression, flat=True)
2289        args = f"({args})" if len(args.split(",")) > 1 else args
2290        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
2291
2292    def lateral_op(self, expression: exp.Lateral) -> str:
2293        cross_apply = expression.args.get("cross_apply")
2294
2295        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2296        if cross_apply is True:
2297            op = "INNER JOIN "
2298        elif cross_apply is False:
2299            op = "LEFT JOIN "
2300        else:
2301            op = ""
2302
2303        return f"{op}LATERAL"
2304
2305    def lateral_sql(self, expression: exp.Lateral) -> str:
2306        this = self.sql(expression, "this")
2307
2308        if expression.args.get("view"):
2309            alias = expression.args["alias"]
2310            columns = self.expressions(alias, key="columns", flat=True)
2311            table = f" {alias.name}" if alias.name else ""
2312            columns = f" AS {columns}" if columns else ""
2313            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2314            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2315
2316        alias = self.sql(expression, "alias")
2317        alias = f" AS {alias}" if alias else ""
2318
2319        ordinality = expression.args.get("ordinality") or ""
2320        if ordinality:
2321            ordinality = f" WITH ORDINALITY{alias}"
2322            alias = ""
2323
2324        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
2325
2326    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2327        this = self.sql(expression, "this")
2328
2329        args = [
2330            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2331            for e in (expression.args.get(k) for k in ("offset", "expression"))
2332            if e
2333        ]
2334
2335        args_sql = ", ".join(self.sql(e) for e in args)
2336        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2337        expressions = self.expressions(expression, flat=True)
2338        limit_options = self.sql(expression, "limit_options")
2339        expressions = f" BY {expressions}" if expressions else ""
2340
2341        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2342
2343    def offset_sql(self, expression: exp.Offset) -> str:
2344        this = self.sql(expression, "this")
2345        value = expression.expression
2346        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2347        expressions = self.expressions(expression, flat=True)
2348        expressions = f" BY {expressions}" if expressions else ""
2349        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2350
2351    def setitem_sql(self, expression: exp.SetItem) -> str:
2352        kind = self.sql(expression, "kind")
2353        kind = f"{kind} " if kind else ""
2354        this = self.sql(expression, "this")
2355        expressions = self.expressions(expression)
2356        collate = self.sql(expression, "collate")
2357        collate = f" COLLATE {collate}" if collate else ""
2358        global_ = "GLOBAL " if expression.args.get("global") else ""
2359        return f"{global_}{kind}{this}{expressions}{collate}"
2360
2361    def set_sql(self, expression: exp.Set) -> str:
2362        expressions = f" {self.expressions(expression, flat=True)}"
2363        tag = " TAG" if expression.args.get("tag") else ""
2364        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2365
2366    def pragma_sql(self, expression: exp.Pragma) -> str:
2367        return f"PRAGMA {self.sql(expression, 'this')}"
2368
2369    def lock_sql(self, expression: exp.Lock) -> str:
2370        if not self.LOCKING_READS_SUPPORTED:
2371            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2372            return ""
2373
2374        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2375        expressions = self.expressions(expression, flat=True)
2376        expressions = f" OF {expressions}" if expressions else ""
2377        wait = expression.args.get("wait")
2378
2379        if wait is not None:
2380            if isinstance(wait, exp.Literal):
2381                wait = f" WAIT {self.sql(wait)}"
2382            else:
2383                wait = " NOWAIT" if wait else " SKIP LOCKED"
2384
2385        return f"{lock_type}{expressions}{wait or ''}"
2386
2387    def literal_sql(self, expression: exp.Literal) -> str:
2388        text = expression.this or ""
2389        if expression.is_string:
2390            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2391        return text
2392
2393    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2394        if self.dialect.ESCAPED_SEQUENCES:
2395            to_escaped = self.dialect.ESCAPED_SEQUENCES
2396            text = "".join(
2397                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2398            )
2399
2400        return self._replace_line_breaks(text).replace(
2401            self.dialect.QUOTE_END, self._escaped_quote_end
2402        )
2403
2404    def loaddata_sql(self, expression: exp.LoadData) -> str:
2405        local = " LOCAL" if expression.args.get("local") else ""
2406        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2407        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2408        this = f" INTO TABLE {self.sql(expression, 'this')}"
2409        partition = self.sql(expression, "partition")
2410        partition = f" {partition}" if partition else ""
2411        input_format = self.sql(expression, "input_format")
2412        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2413        serde = self.sql(expression, "serde")
2414        serde = f" SERDE {serde}" if serde else ""
2415        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2416
2417    def null_sql(self, *_) -> str:
2418        return "NULL"
2419
2420    def boolean_sql(self, expression: exp.Boolean) -> str:
2421        return "TRUE" if expression.this else "FALSE"
2422
2423    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2424        this = self.sql(expression, "this")
2425        this = f"{this} " if this else this
2426        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2427        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
2428
2429    def withfill_sql(self, expression: exp.WithFill) -> str:
2430        from_sql = self.sql(expression, "from")
2431        from_sql = f" FROM {from_sql}" if from_sql else ""
2432        to_sql = self.sql(expression, "to")
2433        to_sql = f" TO {to_sql}" if to_sql else ""
2434        step_sql = self.sql(expression, "step")
2435        step_sql = f" STEP {step_sql}" if step_sql else ""
2436        interpolated_values = [
2437            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2438            if isinstance(e, exp.Alias)
2439            else self.sql(e, "this")
2440            for e in expression.args.get("interpolate") or []
2441        ]
2442        interpolate = (
2443            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2444        )
2445        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2446
2447    def cluster_sql(self, expression: exp.Cluster) -> str:
2448        return self.op_expressions("CLUSTER BY", expression)
2449
2450    def distribute_sql(self, expression: exp.Distribute) -> str:
2451        return self.op_expressions("DISTRIBUTE BY", expression)
2452
2453    def sort_sql(self, expression: exp.Sort) -> str:
2454        return self.op_expressions("SORT BY", expression)
2455
2456    def ordered_sql(self, expression: exp.Ordered) -> str:
2457        desc = expression.args.get("desc")
2458        asc = not desc
2459
2460        nulls_first = expression.args.get("nulls_first")
2461        nulls_last = not nulls_first
2462        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2463        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2464        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2465
2466        this = self.sql(expression, "this")
2467
2468        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2469        nulls_sort_change = ""
2470        if nulls_first and (
2471            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2472        ):
2473            nulls_sort_change = " NULLS FIRST"
2474        elif (
2475            nulls_last
2476            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2477            and not nulls_are_last
2478        ):
2479            nulls_sort_change = " NULLS LAST"
2480
2481        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2482        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2483            window = expression.find_ancestor(exp.Window, exp.Select)
2484            if isinstance(window, exp.Window) and window.args.get("spec"):
2485                self.unsupported(
2486                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2487                )
2488                nulls_sort_change = ""
2489            elif self.NULL_ORDERING_SUPPORTED is False and (
2490                (asc and nulls_sort_change == " NULLS LAST")
2491                or (desc and nulls_sort_change == " NULLS FIRST")
2492            ):
2493                # BigQuery does not allow these ordering/nulls combinations when used under
2494                # an aggregation func or under a window containing one
2495                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2496
2497                if isinstance(ancestor, exp.Window):
2498                    ancestor = ancestor.this
2499                if isinstance(ancestor, exp.AggFunc):
2500                    self.unsupported(
2501                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2502                    )
2503                    nulls_sort_change = ""
2504            elif self.NULL_ORDERING_SUPPORTED is None:
2505                if expression.this.is_int:
2506                    self.unsupported(
2507                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2508                    )
2509                elif not isinstance(expression.this, exp.Rand):
2510                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2511                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2512                nulls_sort_change = ""
2513
2514        with_fill = self.sql(expression, "with_fill")
2515        with_fill = f" {with_fill}" if with_fill else ""
2516
2517        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2518
2519    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2520        window_frame = self.sql(expression, "window_frame")
2521        window_frame = f"{window_frame} " if window_frame else ""
2522
2523        this = self.sql(expression, "this")
2524
2525        return f"{window_frame}{this}"
2526
2527    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2528        partition = self.partition_by_sql(expression)
2529        order = self.sql(expression, "order")
2530        measures = self.expressions(expression, key="measures")
2531        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2532        rows = self.sql(expression, "rows")
2533        rows = self.seg(rows) if rows else ""
2534        after = self.sql(expression, "after")
2535        after = self.seg(after) if after else ""
2536        pattern = self.sql(expression, "pattern")
2537        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2538        definition_sqls = [
2539            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2540            for definition in expression.args.get("define", [])
2541        ]
2542        definitions = self.expressions(sqls=definition_sqls)
2543        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2544        body = "".join(
2545            (
2546                partition,
2547                order,
2548                measures,
2549                rows,
2550                after,
2551                pattern,
2552                define,
2553            )
2554        )
2555        alias = self.sql(expression, "alias")
2556        alias = f" {alias}" if alias else ""
2557        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2558
2559    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2560        limit = expression.args.get("limit")
2561
2562        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2563            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2564        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2565            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2566
2567        return csv(
2568            *sqls,
2569            *[self.sql(join) for join in expression.args.get("joins") or []],
2570            self.sql(expression, "match"),
2571            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2572            self.sql(expression, "prewhere"),
2573            self.sql(expression, "where"),
2574            self.sql(expression, "connect"),
2575            self.sql(expression, "group"),
2576            self.sql(expression, "having"),
2577            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2578            self.sql(expression, "order"),
2579            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2580            *self.after_limit_modifiers(expression),
2581            self.options_modifier(expression),
2582            sep="",
2583        )
2584
2585    def options_modifier(self, expression: exp.Expression) -> str:
2586        options = self.expressions(expression, key="options")
2587        return f" {options}" if options else ""
2588
2589    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2590        self.unsupported("Unsupported query option.")
2591        return ""
2592
2593    def offset_limit_modifiers(
2594        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2595    ) -> t.List[str]:
2596        return [
2597            self.sql(expression, "offset") if fetch else self.sql(limit),
2598            self.sql(limit) if fetch else self.sql(expression, "offset"),
2599        ]
2600
2601    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2602        locks = self.expressions(expression, key="locks", sep=" ")
2603        locks = f" {locks}" if locks else ""
2604        return [locks, self.sql(expression, "sample")]
2605
2606    def select_sql(self, expression: exp.Select) -> str:
2607        into = expression.args.get("into")
2608        if not self.SUPPORTS_SELECT_INTO and into:
2609            into.pop()
2610
2611        hint = self.sql(expression, "hint")
2612        distinct = self.sql(expression, "distinct")
2613        distinct = f" {distinct}" if distinct else ""
2614        kind = self.sql(expression, "kind")
2615
2616        limit = expression.args.get("limit")
2617        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2618            top = self.limit_sql(limit, top=True)
2619            limit.pop()
2620        else:
2621            top = ""
2622
2623        expressions = self.expressions(expression)
2624
2625        if kind:
2626            if kind in self.SELECT_KINDS:
2627                kind = f" AS {kind}"
2628            else:
2629                if kind == "STRUCT":
2630                    expressions = self.expressions(
2631                        sqls=[
2632                            self.sql(
2633                                exp.Struct(
2634                                    expressions=[
2635                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2636                                        if isinstance(e, exp.Alias)
2637                                        else e
2638                                        for e in expression.expressions
2639                                    ]
2640                                )
2641                            )
2642                        ]
2643                    )
2644                kind = ""
2645
2646        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2647        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2648
2649        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2650        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2651        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2652        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2653        sql = self.query_modifiers(
2654            expression,
2655            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2656            self.sql(expression, "into", comment=False),
2657            self.sql(expression, "from", comment=False),
2658        )
2659
2660        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2661        if expression.args.get("with"):
2662            sql = self.maybe_comment(sql, expression)
2663            expression.pop_comments()
2664
2665        sql = self.prepend_ctes(expression, sql)
2666
2667        if not self.SUPPORTS_SELECT_INTO and into:
2668            if into.args.get("temporary"):
2669                table_kind = " TEMPORARY"
2670            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2671                table_kind = " UNLOGGED"
2672            else:
2673                table_kind = ""
2674            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2675
2676        return sql
2677
2678    def schema_sql(self, expression: exp.Schema) -> str:
2679        this = self.sql(expression, "this")
2680        sql = self.schema_columns_sql(expression)
2681        return f"{this} {sql}" if this and sql else this or sql
2682
2683    def schema_columns_sql(self, expression: exp.Schema) -> str:
2684        if expression.expressions:
2685            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2686        return ""
2687
2688    def star_sql(self, expression: exp.Star) -> str:
2689        except_ = self.expressions(expression, key="except", flat=True)
2690        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2691        replace = self.expressions(expression, key="replace", flat=True)
2692        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2693        rename = self.expressions(expression, key="rename", flat=True)
2694        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2695        return f"*{except_}{replace}{rename}"
2696
2697    def parameter_sql(self, expression: exp.Parameter) -> str:
2698        this = self.sql(expression, "this")
2699        return f"{self.PARAMETER_TOKEN}{this}"
2700
2701    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2702        this = self.sql(expression, "this")
2703        kind = expression.text("kind")
2704        if kind:
2705            kind = f"{kind}."
2706        return f"@@{kind}{this}"
2707
2708    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2709        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
2710
2711    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2712        alias = self.sql(expression, "alias")
2713        alias = f"{sep}{alias}" if alias else ""
2714        sample = self.sql(expression, "sample")
2715        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2716            alias = f"{sample}{alias}"
2717
2718            # Set to None so it's not generated again by self.query_modifiers()
2719            expression.set("sample", None)
2720
2721        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2722        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2723        return self.prepend_ctes(expression, sql)
2724
2725    def qualify_sql(self, expression: exp.Qualify) -> str:
2726        this = self.indent(self.sql(expression, "this"))
2727        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
2728
2729    def unnest_sql(self, expression: exp.Unnest) -> str:
2730        args = self.expressions(expression, flat=True)
2731
2732        alias = expression.args.get("alias")
2733        offset = expression.args.get("offset")
2734
2735        if self.UNNEST_WITH_ORDINALITY:
2736            if alias and isinstance(offset, exp.Expression):
2737                alias.append("columns", offset)
2738
2739        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2740            columns = alias.columns
2741            alias = self.sql(columns[0]) if columns else ""
2742        else:
2743            alias = self.sql(alias)
2744
2745        alias = f" AS {alias}" if alias else alias
2746        if self.UNNEST_WITH_ORDINALITY:
2747            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2748        else:
2749            if isinstance(offset, exp.Expression):
2750                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2751            elif offset:
2752                suffix = f"{alias} WITH OFFSET"
2753            else:
2754                suffix = alias
2755
2756        return f"UNNEST({args}){suffix}"
2757
2758    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2759        return ""
2760
2761    def where_sql(self, expression: exp.Where) -> str:
2762        this = self.indent(self.sql(expression, "this"))
2763        return f"{self.seg('WHERE')}{self.sep()}{this}"
2764
2765    def window_sql(self, expression: exp.Window) -> str:
2766        this = self.sql(expression, "this")
2767        partition = self.partition_by_sql(expression)
2768        order = expression.args.get("order")
2769        order = self.order_sql(order, flat=True) if order else ""
2770        spec = self.sql(expression, "spec")
2771        alias = self.sql(expression, "alias")
2772        over = self.sql(expression, "over") or "OVER"
2773
2774        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2775
2776        first = expression.args.get("first")
2777        if first is None:
2778            first = ""
2779        else:
2780            first = "FIRST" if first else "LAST"
2781
2782        if not partition and not order and not spec and alias:
2783            return f"{this} {alias}"
2784
2785        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
2786        return f"{this} ({args})"
2787
2788    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2789        partition = self.expressions(expression, key="partition_by", flat=True)
2790        return f"PARTITION BY {partition}" if partition else ""
2791
2792    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2793        kind = self.sql(expression, "kind")
2794        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2795        end = (
2796            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2797            or "CURRENT ROW"
2798        )
2799        return f"{kind} BETWEEN {start} AND {end}"
2800
2801    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2802        this = self.sql(expression, "this")
2803        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2804        return f"{this} WITHIN GROUP ({expression_sql})"
2805
2806    def between_sql(self, expression: exp.Between) -> str:
2807        this = self.sql(expression, "this")
2808        low = self.sql(expression, "low")
2809        high = self.sql(expression, "high")
2810        return f"{this} BETWEEN {low} AND {high}"
2811
2812    def bracket_offset_expressions(
2813        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2814    ) -> t.List[exp.Expression]:
2815        return apply_index_offset(
2816            expression.this,
2817            expression.expressions,
2818            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2819            dialect=self.dialect,
2820        )
2821
2822    def bracket_sql(self, expression: exp.Bracket) -> str:
2823        expressions = self.bracket_offset_expressions(expression)
2824        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2825        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
2826
2827    def all_sql(self, expression: exp.All) -> str:
2828        return f"ALL {self.wrap(expression)}"
2829
2830    def any_sql(self, expression: exp.Any) -> str:
2831        this = self.sql(expression, "this")
2832        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2833            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2834                this = self.wrap(this)
2835            return f"ANY{this}"
2836        return f"ANY {this}"
2837
2838    def exists_sql(self, expression: exp.Exists) -> str:
2839        return f"EXISTS{self.wrap(expression)}"
2840
2841    def case_sql(self, expression: exp.Case) -> str:
2842        this = self.sql(expression, "this")
2843        statements = [f"CASE {this}" if this else "CASE"]
2844
2845        for e in expression.args["ifs"]:
2846            statements.append(f"WHEN {self.sql(e, 'this')}")
2847            statements.append(f"THEN {self.sql(e, 'true')}")
2848
2849        default = self.sql(expression, "default")
2850
2851        if default:
2852            statements.append(f"ELSE {default}")
2853
2854        statements.append("END")
2855
2856        if self.pretty and self.too_wide(statements):
2857            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2858
2859        return " ".join(statements)
2860
2861    def constraint_sql(self, expression: exp.Constraint) -> str:
2862        this = self.sql(expression, "this")
2863        expressions = self.expressions(expression, flat=True)
2864        return f"CONSTRAINT {this} {expressions}"
2865
2866    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2867        order = expression.args.get("order")
2868        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2869        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
2870
2871    def extract_sql(self, expression: exp.Extract) -> str:
2872        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2873        expression_sql = self.sql(expression, "expression")
2874        return f"EXTRACT({this} FROM {expression_sql})"
2875
2876    def trim_sql(self, expression: exp.Trim) -> str:
2877        trim_type = self.sql(expression, "position")
2878
2879        if trim_type == "LEADING":
2880            func_name = "LTRIM"
2881        elif trim_type == "TRAILING":
2882            func_name = "RTRIM"
2883        else:
2884            func_name = "TRIM"
2885
2886        return self.func(func_name, expression.this, expression.expression)
2887
2888    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2889        args = expression.expressions
2890        if isinstance(expression, exp.ConcatWs):
2891            args = args[1:]  # Skip the delimiter
2892
2893        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2894            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2895
2896        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2897            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2898
2899        return args
2900
2901    def concat_sql(self, expression: exp.Concat) -> str:
2902        expressions = self.convert_concat_args(expression)
2903
2904        # Some dialects don't allow a single-argument CONCAT call
2905        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2906            return self.sql(expressions[0])
2907
2908        return self.func("CONCAT", *expressions)
2909
2910    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2911        return self.func(
2912            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2913        )
2914
2915    def check_sql(self, expression: exp.Check) -> str:
2916        this = self.sql(expression, key="this")
2917        return f"CHECK ({this})"
2918
2919    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2920        expressions = self.expressions(expression, flat=True)
2921        expressions = f" ({expressions})" if expressions else ""
2922        reference = self.sql(expression, "reference")
2923        reference = f" {reference}" if reference else ""
2924        delete = self.sql(expression, "delete")
2925        delete = f" ON DELETE {delete}" if delete else ""
2926        update = self.sql(expression, "update")
2927        update = f" ON UPDATE {update}" if update else ""
2928        options = self.expressions(expression, key="options", flat=True, sep=" ")
2929        options = f" {options}" if options else ""
2930        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
2931
2932    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2933        expressions = self.expressions(expression, flat=True)
2934        options = self.expressions(expression, key="options", flat=True, sep=" ")
2935        options = f" {options}" if options else ""
2936        return f"PRIMARY KEY ({expressions}){options}"
2937
2938    def if_sql(self, expression: exp.If) -> str:
2939        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
2940
2941    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2942        modifier = expression.args.get("modifier")
2943        modifier = f" {modifier}" if modifier else ""
2944        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
2945
2946    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2947        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
2948
2949    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2950        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2951
2952        if expression.args.get("escape"):
2953            path = self.escape_str(path)
2954
2955        if self.QUOTE_JSON_PATH:
2956            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2957
2958        return path
2959
2960    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
2961        if isinstance(expression, exp.JSONPathPart):
2962            transform = self.TRANSFORMS.get(expression.__class__)
2963            if not callable(transform):
2964                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
2965                return ""
2966
2967            return transform(self, expression)
2968
2969        if isinstance(expression, int):
2970            return str(expression)
2971
2972        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
2973            escaped = expression.replace("'", "\\'")
2974            escaped = f"\\'{expression}\\'"
2975        else:
2976            escaped = expression.replace('"', '\\"')
2977            escaped = f'"{escaped}"'
2978
2979        return escaped
2980
2981    def formatjson_sql(self, expression: exp.FormatJson) -> str:
2982        return f"{self.sql(expression, 'this')} FORMAT JSON"
2983
2984    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
2985        null_handling = expression.args.get("null_handling")
2986        null_handling = f" {null_handling}" if null_handling else ""
2987
2988        unique_keys = expression.args.get("unique_keys")
2989        if unique_keys is not None:
2990            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
2991        else:
2992            unique_keys = ""
2993
2994        return_type = self.sql(expression, "return_type")
2995        return_type = f" RETURNING {return_type}" if return_type else ""
2996        encoding = self.sql(expression, "encoding")
2997        encoding = f" ENCODING {encoding}" if encoding else ""
2998
2999        return self.func(
3000            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3001            *expression.expressions,
3002            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3003        )
3004
3005    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3006        return self.jsonobject_sql(expression)
3007
3008    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3009        null_handling = expression.args.get("null_handling")
3010        null_handling = f" {null_handling}" if null_handling else ""
3011        return_type = self.sql(expression, "return_type")
3012        return_type = f" RETURNING {return_type}" if return_type else ""
3013        strict = " STRICT" if expression.args.get("strict") else ""
3014        return self.func(
3015            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3016        )
3017
3018    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3019        this = self.sql(expression, "this")
3020        order = self.sql(expression, "order")
3021        null_handling = expression.args.get("null_handling")
3022        null_handling = f" {null_handling}" if null_handling else ""
3023        return_type = self.sql(expression, "return_type")
3024        return_type = f" RETURNING {return_type}" if return_type else ""
3025        strict = " STRICT" if expression.args.get("strict") else ""
3026        return self.func(
3027            "JSON_ARRAYAGG",
3028            this,
3029            suffix=f"{order}{null_handling}{return_type}{strict})",
3030        )
3031
3032    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3033        path = self.sql(expression, "path")
3034        path = f" PATH {path}" if path else ""
3035        nested_schema = self.sql(expression, "nested_schema")
3036
3037        if nested_schema:
3038            return f"NESTED{path} {nested_schema}"
3039
3040        this = self.sql(expression, "this")
3041        kind = self.sql(expression, "kind")
3042        kind = f" {kind}" if kind else ""
3043        return f"{this}{kind}{path}"
3044
3045    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3046        return self.func("COLUMNS", *expression.expressions)
3047
3048    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3049        this = self.sql(expression, "this")
3050        path = self.sql(expression, "path")
3051        path = f", {path}" if path else ""
3052        error_handling = expression.args.get("error_handling")
3053        error_handling = f" {error_handling}" if error_handling else ""
3054        empty_handling = expression.args.get("empty_handling")
3055        empty_handling = f" {empty_handling}" if empty_handling else ""
3056        schema = self.sql(expression, "schema")
3057        return self.func(
3058            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3059        )
3060
3061    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3062        this = self.sql(expression, "this")
3063        kind = self.sql(expression, "kind")
3064        path = self.sql(expression, "path")
3065        path = f" {path}" if path else ""
3066        as_json = " AS JSON" if expression.args.get("as_json") else ""
3067        return f"{this} {kind}{path}{as_json}"
3068
3069    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3070        this = self.sql(expression, "this")
3071        path = self.sql(expression, "path")
3072        path = f", {path}" if path else ""
3073        expressions = self.expressions(expression)
3074        with_ = (
3075            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3076            if expressions
3077            else ""
3078        )
3079        return f"OPENJSON({this}{path}){with_}"
3080
3081    def in_sql(self, expression: exp.In) -> str:
3082        query = expression.args.get("query")
3083        unnest = expression.args.get("unnest")
3084        field = expression.args.get("field")
3085        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3086
3087        if query:
3088            in_sql = self.sql(query)
3089        elif unnest:
3090            in_sql = self.in_unnest_op(unnest)
3091        elif field:
3092            in_sql = self.sql(field)
3093        else:
3094            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3095
3096        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3097
3098    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3099        return f"(SELECT {self.sql(unnest)})"
3100
3101    def interval_sql(self, expression: exp.Interval) -> str:
3102        unit = self.sql(expression, "unit")
3103        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3104            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3105        unit = f" {unit}" if unit else ""
3106
3107        if self.SINGLE_STRING_INTERVAL:
3108            this = expression.this.name if expression.this else ""
3109            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3110
3111        this = self.sql(expression, "this")
3112        if this:
3113            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3114            this = f" {this}" if unwrapped else f" ({this})"
3115
3116        return f"INTERVAL{this}{unit}"
3117
3118    def return_sql(self, expression: exp.Return) -> str:
3119        return f"RETURN {self.sql(expression, 'this')}"
3120
3121    def reference_sql(self, expression: exp.Reference) -> str:
3122        this = self.sql(expression, "this")
3123        expressions = self.expressions(expression, flat=True)
3124        expressions = f"({expressions})" if expressions else ""
3125        options = self.expressions(expression, key="options", flat=True, sep=" ")
3126        options = f" {options}" if options else ""
3127        return f"REFERENCES {this}{expressions}{options}"
3128
3129    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3130        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3131        parent = expression.parent
3132        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3133        return self.func(
3134            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3135        )
3136
3137    def paren_sql(self, expression: exp.Paren) -> str:
3138        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3139        return f"({sql}{self.seg(')', sep='')}"
3140
3141    def neg_sql(self, expression: exp.Neg) -> str:
3142        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3143        this_sql = self.sql(expression, "this")
3144        sep = " " if this_sql[0] == "-" else ""
3145        return f"-{sep}{this_sql}"
3146
3147    def not_sql(self, expression: exp.Not) -> str:
3148        return f"NOT {self.sql(expression, 'this')}"
3149
3150    def alias_sql(self, expression: exp.Alias) -> str:
3151        alias = self.sql(expression, "alias")
3152        alias = f" AS {alias}" if alias else ""
3153        return f"{self.sql(expression, 'this')}{alias}"
3154
3155    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3156        alias = expression.args["alias"]
3157
3158        parent = expression.parent
3159        pivot = parent and parent.parent
3160
3161        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3162            identifier_alias = isinstance(alias, exp.Identifier)
3163            literal_alias = isinstance(alias, exp.Literal)
3164
3165            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3166                alias.replace(exp.Literal.string(alias.output_name))
3167            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3168                alias.replace(exp.to_identifier(alias.output_name))
3169
3170        return self.alias_sql(expression)
3171
3172    def aliases_sql(self, expression: exp.Aliases) -> str:
3173        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
3174
3175    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3176        this = self.sql(expression, "this")
3177        index = self.sql(expression, "expression")
3178        return f"{this} AT {index}"
3179
3180    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3181        this = self.sql(expression, "this")
3182        zone = self.sql(expression, "zone")
3183        return f"{this} AT TIME ZONE {zone}"
3184
3185    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3186        this = self.sql(expression, "this")
3187        zone = self.sql(expression, "zone")
3188        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
3189
3190    def add_sql(self, expression: exp.Add) -> str:
3191        return self.binary(expression, "+")
3192
3193    def and_sql(
3194        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3195    ) -> str:
3196        return self.connector_sql(expression, "AND", stack)
3197
3198    def or_sql(
3199        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3200    ) -> str:
3201        return self.connector_sql(expression, "OR", stack)
3202
3203    def xor_sql(
3204        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3205    ) -> str:
3206        return self.connector_sql(expression, "XOR", stack)
3207
3208    def connector_sql(
3209        self,
3210        expression: exp.Connector,
3211        op: str,
3212        stack: t.Optional[t.List[str | exp.Expression]] = None,
3213    ) -> str:
3214        if stack is not None:
3215            if expression.expressions:
3216                stack.append(self.expressions(expression, sep=f" {op} "))
3217            else:
3218                stack.append(expression.right)
3219                if expression.comments and self.comments:
3220                    for comment in expression.comments:
3221                        if comment:
3222                            op += f" /*{self.pad_comment(comment)}*/"
3223                stack.extend((op, expression.left))
3224            return op
3225
3226        stack = [expression]
3227        sqls: t.List[str] = []
3228        ops = set()
3229
3230        while stack:
3231            node = stack.pop()
3232            if isinstance(node, exp.Connector):
3233                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3234            else:
3235                sql = self.sql(node)
3236                if sqls and sqls[-1] in ops:
3237                    sqls[-1] += f" {sql}"
3238                else:
3239                    sqls.append(sql)
3240
3241        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3242        return sep.join(sqls)
3243
3244    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3245        return self.binary(expression, "&")
3246
3247    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3248        return self.binary(expression, "<<")
3249
3250    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3251        return f"~{self.sql(expression, 'this')}"
3252
3253    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3254        return self.binary(expression, "|")
3255
3256    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3257        return self.binary(expression, ">>")
3258
3259    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3260        return self.binary(expression, "^")
3261
3262    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3263        format_sql = self.sql(expression, "format")
3264        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3265        to_sql = self.sql(expression, "to")
3266        to_sql = f" {to_sql}" if to_sql else ""
3267        action = self.sql(expression, "action")
3268        action = f" {action}" if action else ""
3269        default = self.sql(expression, "default")
3270        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3271        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3272
3273    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3274        zone = self.sql(expression, "this")
3275        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
3276
3277    def collate_sql(self, expression: exp.Collate) -> str:
3278        if self.COLLATE_IS_FUNC:
3279            return self.function_fallback_sql(expression)
3280        return self.binary(expression, "COLLATE")
3281
3282    def command_sql(self, expression: exp.Command) -> str:
3283        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
3284
3285    def comment_sql(self, expression: exp.Comment) -> str:
3286        this = self.sql(expression, "this")
3287        kind = expression.args["kind"]
3288        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3289        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3290        expression_sql = self.sql(expression, "expression")
3291        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3292
3293    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3294        this = self.sql(expression, "this")
3295        delete = " DELETE" if expression.args.get("delete") else ""
3296        recompress = self.sql(expression, "recompress")
3297        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3298        to_disk = self.sql(expression, "to_disk")
3299        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3300        to_volume = self.sql(expression, "to_volume")
3301        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3302        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3303
3304    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3305        where = self.sql(expression, "where")
3306        group = self.sql(expression, "group")
3307        aggregates = self.expressions(expression, key="aggregates")
3308        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3309
3310        if not (where or group or aggregates) and len(expression.expressions) == 1:
3311            return f"TTL {self.expressions(expression, flat=True)}"
3312
3313        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3314
3315    def transaction_sql(self, expression: exp.Transaction) -> str:
3316        return "BEGIN"
3317
3318    def commit_sql(self, expression: exp.Commit) -> str:
3319        chain = expression.args.get("chain")
3320        if chain is not None:
3321            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3322
3323        return f"COMMIT{chain or ''}"
3324
3325    def rollback_sql(self, expression: exp.Rollback) -> str:
3326        savepoint = expression.args.get("savepoint")
3327        savepoint = f" TO {savepoint}" if savepoint else ""
3328        return f"ROLLBACK{savepoint}"
3329
3330    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3331        this = self.sql(expression, "this")
3332
3333        dtype = self.sql(expression, "dtype")
3334        if dtype:
3335            collate = self.sql(expression, "collate")
3336            collate = f" COLLATE {collate}" if collate else ""
3337            using = self.sql(expression, "using")
3338            using = f" USING {using}" if using else ""
3339            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
3340
3341        default = self.sql(expression, "default")
3342        if default:
3343            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3344
3345        comment = self.sql(expression, "comment")
3346        if comment:
3347            return f"ALTER COLUMN {this} COMMENT {comment}"
3348
3349        visible = expression.args.get("visible")
3350        if visible:
3351            return f"ALTER COLUMN {this} SET {visible}"
3352
3353        allow_null = expression.args.get("allow_null")
3354        drop = expression.args.get("drop")
3355
3356        if not drop and not allow_null:
3357            self.unsupported("Unsupported ALTER COLUMN syntax")
3358
3359        if allow_null is not None:
3360            keyword = "DROP" if drop else "SET"
3361            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3362
3363        return f"ALTER COLUMN {this} DROP DEFAULT"
3364
3365    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3366        this = self.sql(expression, "this")
3367
3368        visible = expression.args.get("visible")
3369        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3370
3371        return f"ALTER INDEX {this} {visible_sql}"
3372
3373    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3374        this = self.sql(expression, "this")
3375        if not isinstance(expression.this, exp.Var):
3376            this = f"KEY DISTKEY {this}"
3377        return f"ALTER DISTSTYLE {this}"
3378
3379    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3380        compound = " COMPOUND" if expression.args.get("compound") else ""
3381        this = self.sql(expression, "this")
3382        expressions = self.expressions(expression, flat=True)
3383        expressions = f"({expressions})" if expressions else ""
3384        return f"ALTER{compound} SORTKEY {this or expressions}"
3385
3386    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3387        if not self.RENAME_TABLE_WITH_DB:
3388            # Remove db from tables
3389            expression = expression.transform(
3390                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3391            ).assert_is(exp.AlterRename)
3392        this = self.sql(expression, "this")
3393        return f"RENAME TO {this}"
3394
3395    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3396        exists = " IF EXISTS" if expression.args.get("exists") else ""
3397        old_column = self.sql(expression, "this")
3398        new_column = self.sql(expression, "to")
3399        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
3400
3401    def alterset_sql(self, expression: exp.AlterSet) -> str:
3402        exprs = self.expressions(expression, flat=True)
3403        return f"SET {exprs}"
3404
3405    def alter_sql(self, expression: exp.Alter) -> str:
3406        actions = expression.args["actions"]
3407
3408        if isinstance(actions[0], exp.ColumnDef):
3409            actions = self.add_column_sql(expression)
3410        elif isinstance(actions[0], exp.Schema):
3411            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
3412        elif isinstance(actions[0], exp.Delete):
3413            actions = self.expressions(expression, key="actions", flat=True)
3414        elif isinstance(actions[0], exp.Query):
3415            actions = "AS " + self.expressions(expression, key="actions")
3416        else:
3417            actions = self.expressions(expression, key="actions", flat=True)
3418
3419        exists = " IF EXISTS" if expression.args.get("exists") else ""
3420        on_cluster = self.sql(expression, "cluster")
3421        on_cluster = f" {on_cluster}" if on_cluster else ""
3422        only = " ONLY" if expression.args.get("only") else ""
3423        options = self.expressions(expression, key="options")
3424        options = f", {options}" if options else ""
3425        kind = self.sql(expression, "kind")
3426        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3427
3428        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3429
3430    def add_column_sql(self, expression: exp.Alter) -> str:
3431        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3432            return self.expressions(
3433                expression,
3434                key="actions",
3435                prefix="ADD COLUMN ",
3436                skip_first=True,
3437            )
3438        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3439
3440    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3441        expressions = self.expressions(expression)
3442        exists = " IF EXISTS " if expression.args.get("exists") else " "
3443        return f"DROP{exists}{expressions}"
3444
3445    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3446        return f"ADD {self.expressions(expression)}"
3447
3448    def distinct_sql(self, expression: exp.Distinct) -> str:
3449        this = self.expressions(expression, flat=True)
3450
3451        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3452            case = exp.case()
3453            for arg in expression.expressions:
3454                case = case.when(arg.is_(exp.null()), exp.null())
3455            this = self.sql(case.else_(f"({this})"))
3456
3457        this = f" {this}" if this else ""
3458
3459        on = self.sql(expression, "on")
3460        on = f" ON {on}" if on else ""
3461        return f"DISTINCT{this}{on}"
3462
3463    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3464        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
3465
3466    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3467        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
3468
3469    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3470        this_sql = self.sql(expression, "this")
3471        expression_sql = self.sql(expression, "expression")
3472        kind = "MAX" if expression.args.get("max") else "MIN"
3473        return f"{this_sql} HAVING {kind} {expression_sql}"
3474
3475    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3476        return self.sql(
3477            exp.Cast(
3478                this=exp.Div(this=expression.this, expression=expression.expression),
3479                to=exp.DataType(this=exp.DataType.Type.INT),
3480            )
3481        )
3482
3483    def dpipe_sql(self, expression: exp.DPipe) -> str:
3484        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3485            return self.func(
3486                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3487            )
3488        return self.binary(expression, "||")
3489
3490    def div_sql(self, expression: exp.Div) -> str:
3491        l, r = expression.left, expression.right
3492
3493        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3494            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3495
3496        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3497            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3498                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3499
3500        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3501            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3502                return self.sql(
3503                    exp.cast(
3504                        l / r,
3505                        to=exp.DataType.Type.BIGINT,
3506                    )
3507                )
3508
3509        return self.binary(expression, "/")
3510
3511    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3512        n = exp._wrap(expression.this, exp.Binary)
3513        d = exp._wrap(expression.expression, exp.Binary)
3514        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
3515
3516    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3517        return self.binary(expression, "OVERLAPS")
3518
3519    def distance_sql(self, expression: exp.Distance) -> str:
3520        return self.binary(expression, "<->")
3521
3522    def dot_sql(self, expression: exp.Dot) -> str:
3523        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
3524
3525    def eq_sql(self, expression: exp.EQ) -> str:
3526        return self.binary(expression, "=")
3527
3528    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3529        return self.binary(expression, ":=")
3530
3531    def escape_sql(self, expression: exp.Escape) -> str:
3532        return self.binary(expression, "ESCAPE")
3533
3534    def glob_sql(self, expression: exp.Glob) -> str:
3535        return self.binary(expression, "GLOB")
3536
3537    def gt_sql(self, expression: exp.GT) -> str:
3538        return self.binary(expression, ">")
3539
3540    def gte_sql(self, expression: exp.GTE) -> str:
3541        return self.binary(expression, ">=")
3542
3543    def ilike_sql(self, expression: exp.ILike) -> str:
3544        return self.binary(expression, "ILIKE")
3545
3546    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3547        return self.binary(expression, "ILIKE ANY")
3548
3549    def is_sql(self, expression: exp.Is) -> str:
3550        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3551            return self.sql(
3552                expression.this if expression.expression.this else exp.not_(expression.this)
3553            )
3554        return self.binary(expression, "IS")
3555
3556    def like_sql(self, expression: exp.Like) -> str:
3557        return self.binary(expression, "LIKE")
3558
3559    def likeany_sql(self, expression: exp.LikeAny) -> str:
3560        return self.binary(expression, "LIKE ANY")
3561
3562    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3563        return self.binary(expression, "SIMILAR TO")
3564
3565    def lt_sql(self, expression: exp.LT) -> str:
3566        return self.binary(expression, "<")
3567
3568    def lte_sql(self, expression: exp.LTE) -> str:
3569        return self.binary(expression, "<=")
3570
3571    def mod_sql(self, expression: exp.Mod) -> str:
3572        return self.binary(expression, "%")
3573
3574    def mul_sql(self, expression: exp.Mul) -> str:
3575        return self.binary(expression, "*")
3576
3577    def neq_sql(self, expression: exp.NEQ) -> str:
3578        return self.binary(expression, "<>")
3579
3580    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3581        return self.binary(expression, "IS NOT DISTINCT FROM")
3582
3583    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3584        return self.binary(expression, "IS DISTINCT FROM")
3585
3586    def slice_sql(self, expression: exp.Slice) -> str:
3587        return self.binary(expression, ":")
3588
3589    def sub_sql(self, expression: exp.Sub) -> str:
3590        return self.binary(expression, "-")
3591
3592    def trycast_sql(self, expression: exp.TryCast) -> str:
3593        return self.cast_sql(expression, safe_prefix="TRY_")
3594
3595    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3596        return self.cast_sql(expression)
3597
3598    def try_sql(self, expression: exp.Try) -> str:
3599        if not self.TRY_SUPPORTED:
3600            self.unsupported("Unsupported TRY function")
3601            return self.sql(expression, "this")
3602
3603        return self.func("TRY", expression.this)
3604
3605    def log_sql(self, expression: exp.Log) -> str:
3606        this = expression.this
3607        expr = expression.expression
3608
3609        if self.dialect.LOG_BASE_FIRST is False:
3610            this, expr = expr, this
3611        elif self.dialect.LOG_BASE_FIRST is None and expr:
3612            if this.name in ("2", "10"):
3613                return self.func(f"LOG{this.name}", expr)
3614
3615            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3616
3617        return self.func("LOG", this, expr)
3618
3619    def use_sql(self, expression: exp.Use) -> str:
3620        kind = self.sql(expression, "kind")
3621        kind = f" {kind}" if kind else ""
3622        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3623        this = f" {this}" if this else ""
3624        return f"USE{kind}{this}"
3625
3626    def binary(self, expression: exp.Binary, op: str) -> str:
3627        sqls: t.List[str] = []
3628        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3629        binary_type = type(expression)
3630
3631        while stack:
3632            node = stack.pop()
3633
3634            if type(node) is binary_type:
3635                op_func = node.args.get("operator")
3636                if op_func:
3637                    op = f"OPERATOR({self.sql(op_func)})"
3638
3639                stack.append(node.right)
3640                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3641                stack.append(node.left)
3642            else:
3643                sqls.append(self.sql(node))
3644
3645        return "".join(sqls)
3646
3647    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3648        to_clause = self.sql(expression, "to")
3649        if to_clause:
3650            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3651
3652        return self.function_fallback_sql(expression)
3653
3654    def function_fallback_sql(self, expression: exp.Func) -> str:
3655        args = []
3656
3657        for key in expression.arg_types:
3658            arg_value = expression.args.get(key)
3659
3660            if isinstance(arg_value, list):
3661                for value in arg_value:
3662                    args.append(value)
3663            elif arg_value is not None:
3664                args.append(arg_value)
3665
3666        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3667            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3668        else:
3669            name = expression.sql_name()
3670
3671        return self.func(name, *args)
3672
3673    def func(
3674        self,
3675        name: str,
3676        *args: t.Optional[exp.Expression | str],
3677        prefix: str = "(",
3678        suffix: str = ")",
3679        normalize: bool = True,
3680    ) -> str:
3681        name = self.normalize_func(name) if normalize else name
3682        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
3683
3684    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3685        arg_sqls = tuple(
3686            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3687        )
3688        if self.pretty and self.too_wide(arg_sqls):
3689            return self.indent(
3690                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3691            )
3692        return sep.join(arg_sqls)
3693
3694    def too_wide(self, args: t.Iterable) -> bool:
3695        return sum(len(arg) for arg in args) > self.max_text_width
3696
3697    def format_time(
3698        self,
3699        expression: exp.Expression,
3700        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3701        inverse_time_trie: t.Optional[t.Dict] = None,
3702    ) -> t.Optional[str]:
3703        return format_time(
3704            self.sql(expression, "format"),
3705            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3706            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3707        )
3708
3709    def expressions(
3710        self,
3711        expression: t.Optional[exp.Expression] = None,
3712        key: t.Optional[str] = None,
3713        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3714        flat: bool = False,
3715        indent: bool = True,
3716        skip_first: bool = False,
3717        skip_last: bool = False,
3718        sep: str = ", ",
3719        prefix: str = "",
3720        dynamic: bool = False,
3721        new_line: bool = False,
3722    ) -> str:
3723        expressions = expression.args.get(key or "expressions") if expression else sqls
3724
3725        if not expressions:
3726            return ""
3727
3728        if flat:
3729            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3730
3731        num_sqls = len(expressions)
3732        result_sqls = []
3733
3734        for i, e in enumerate(expressions):
3735            sql = self.sql(e, comment=False)
3736            if not sql:
3737                continue
3738
3739            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3740
3741            if self.pretty:
3742                if self.leading_comma:
3743                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3744                else:
3745                    result_sqls.append(
3746                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3747                    )
3748            else:
3749                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3750
3751        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3752            if new_line:
3753                result_sqls.insert(0, "")
3754                result_sqls.append("")
3755            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3756        else:
3757            result_sql = "".join(result_sqls)
3758
3759        return (
3760            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3761            if indent
3762            else result_sql
3763        )
3764
3765    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3766        flat = flat or isinstance(expression.parent, exp.Properties)
3767        expressions_sql = self.expressions(expression, flat=flat)
3768        if flat:
3769            return f"{op} {expressions_sql}"
3770        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3771
3772    def naked_property(self, expression: exp.Property) -> str:
3773        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3774        if not property_name:
3775            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3776        return f"{property_name} {self.sql(expression, 'this')}"
3777
3778    def tag_sql(self, expression: exp.Tag) -> str:
3779        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
3780
3781    def token_sql(self, token_type: TokenType) -> str:
3782        return self.TOKEN_MAPPING.get(token_type, token_type.name)
3783
3784    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3785        this = self.sql(expression, "this")
3786        expressions = self.no_identify(self.expressions, expression)
3787        expressions = (
3788            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3789        )
3790        return f"{this}{expressions}" if expressions.strip() != "" else this
3791
3792    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3793        this = self.sql(expression, "this")
3794        expressions = self.expressions(expression, flat=True)
3795        return f"{this}({expressions})"
3796
3797    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3798        return self.binary(expression, "=>")
3799
3800    def when_sql(self, expression: exp.When) -> str:
3801        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3802        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3803        condition = self.sql(expression, "condition")
3804        condition = f" AND {condition}" if condition else ""
3805
3806        then_expression = expression.args.get("then")
3807        if isinstance(then_expression, exp.Insert):
3808            this = self.sql(then_expression, "this")
3809            this = f"INSERT {this}" if this else "INSERT"
3810            then = self.sql(then_expression, "expression")
3811            then = f"{this} VALUES {then}" if then else this
3812        elif isinstance(then_expression, exp.Update):
3813            if isinstance(then_expression.args.get("expressions"), exp.Star):
3814                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3815            else:
3816                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
3817        else:
3818            then = self.sql(then_expression)
3819        return f"WHEN {matched}{source}{condition} THEN {then}"
3820
3821    def whens_sql(self, expression: exp.Whens) -> str:
3822        return self.expressions(expression, sep=" ", indent=False)
3823
3824    def merge_sql(self, expression: exp.Merge) -> str:
3825        table = expression.this
3826        table_alias = ""
3827
3828        hints = table.args.get("hints")
3829        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3830            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3831            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3832
3833        this = self.sql(table)
3834        using = f"USING {self.sql(expression, 'using')}"
3835        on = f"ON {self.sql(expression, 'on')}"
3836        whens = self.sql(expression, "whens")
3837
3838        returning = self.sql(expression, "returning")
3839        if returning:
3840            whens = f"{whens}{returning}"
3841
3842        sep = self.sep()
3843
3844        return self.prepend_ctes(
3845            expression,
3846            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3847        )
3848
3849    @unsupported_args("format")
3850    def tochar_sql(self, expression: exp.ToChar) -> str:
3851        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
3852
3853    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3854        if not self.SUPPORTS_TO_NUMBER:
3855            self.unsupported("Unsupported TO_NUMBER function")
3856            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3857
3858        fmt = expression.args.get("format")
3859        if not fmt:
3860            self.unsupported("Conversion format is required for TO_NUMBER")
3861            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3862
3863        return self.func("TO_NUMBER", expression.this, fmt)
3864
3865    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3866        this = self.sql(expression, "this")
3867        kind = self.sql(expression, "kind")
3868        settings_sql = self.expressions(expression, key="settings", sep=" ")
3869        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3870        return f"{this}({kind}{args})"
3871
3872    def dictrange_sql(self, expression: exp.DictRange) -> str:
3873        this = self.sql(expression, "this")
3874        max = self.sql(expression, "max")
3875        min = self.sql(expression, "min")
3876        return f"{this}(MIN {min} MAX {max})"
3877
3878    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3879        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
3880
3881    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3882        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
3883
3884    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
3885    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3886        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
3887
3888    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
3889    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3890        expressions = self.expressions(expression, flat=True)
3891        expressions = f" {self.wrap(expressions)}" if expressions else ""
3892        buckets = self.sql(expression, "buckets")
3893        kind = self.sql(expression, "kind")
3894        buckets = f" BUCKETS {buckets}" if buckets else ""
3895        order = self.sql(expression, "order")
3896        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3897
3898    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3899        return ""
3900
3901    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3902        expressions = self.expressions(expression, key="expressions", flat=True)
3903        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3904        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3905        buckets = self.sql(expression, "buckets")
3906        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3907
3908    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3909        this = self.sql(expression, "this")
3910        having = self.sql(expression, "having")
3911
3912        if having:
3913            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3914
3915        return self.func("ANY_VALUE", this)
3916
3917    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3918        transform = self.func("TRANSFORM", *expression.expressions)
3919        row_format_before = self.sql(expression, "row_format_before")
3920        row_format_before = f" {row_format_before}" if row_format_before else ""
3921        record_writer = self.sql(expression, "record_writer")
3922        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3923        using = f" USING {self.sql(expression, 'command_script')}"
3924        schema = self.sql(expression, "schema")
3925        schema = f" AS {schema}" if schema else ""
3926        row_format_after = self.sql(expression, "row_format_after")
3927        row_format_after = f" {row_format_after}" if row_format_after else ""
3928        record_reader = self.sql(expression, "record_reader")
3929        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3930        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3931
3932    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3933        key_block_size = self.sql(expression, "key_block_size")
3934        if key_block_size:
3935            return f"KEY_BLOCK_SIZE = {key_block_size}"
3936
3937        using = self.sql(expression, "using")
3938        if using:
3939            return f"USING {using}"
3940
3941        parser = self.sql(expression, "parser")
3942        if parser:
3943            return f"WITH PARSER {parser}"
3944
3945        comment = self.sql(expression, "comment")
3946        if comment:
3947            return f"COMMENT {comment}"
3948
3949        visible = expression.args.get("visible")
3950        if visible is not None:
3951            return "VISIBLE" if visible else "INVISIBLE"
3952
3953        engine_attr = self.sql(expression, "engine_attr")
3954        if engine_attr:
3955            return f"ENGINE_ATTRIBUTE = {engine_attr}"
3956
3957        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
3958        if secondary_engine_attr:
3959            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
3960
3961        self.unsupported("Unsupported index constraint option.")
3962        return ""
3963
3964    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
3965        enforced = " ENFORCED" if expression.args.get("enforced") else ""
3966        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
3967
3968    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
3969        kind = self.sql(expression, "kind")
3970        kind = f"{kind} INDEX" if kind else "INDEX"
3971        this = self.sql(expression, "this")
3972        this = f" {this}" if this else ""
3973        index_type = self.sql(expression, "index_type")
3974        index_type = f" USING {index_type}" if index_type else ""
3975        expressions = self.expressions(expression, flat=True)
3976        expressions = f" ({expressions})" if expressions else ""
3977        options = self.expressions(expression, key="options", sep=" ")
3978        options = f" {options}" if options else ""
3979        return f"{kind}{this}{index_type}{expressions}{options}"
3980
3981    def nvl2_sql(self, expression: exp.Nvl2) -> str:
3982        if self.NVL2_SUPPORTED:
3983            return self.function_fallback_sql(expression)
3984
3985        case = exp.Case().when(
3986            expression.this.is_(exp.null()).not_(copy=False),
3987            expression.args["true"],
3988            copy=False,
3989        )
3990        else_cond = expression.args.get("false")
3991        if else_cond:
3992            case.else_(else_cond, copy=False)
3993
3994        return self.sql(case)
3995
3996    def comprehension_sql(self, expression: exp.Comprehension) -> str:
3997        this = self.sql(expression, "this")
3998        expr = self.sql(expression, "expression")
3999        iterator = self.sql(expression, "iterator")
4000        condition = self.sql(expression, "condition")
4001        condition = f" IF {condition}" if condition else ""
4002        return f"{this} FOR {expr} IN {iterator}{condition}"
4003
4004    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4005        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
4006
4007    def opclass_sql(self, expression: exp.Opclass) -> str:
4008        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
4009
4010    def predict_sql(self, expression: exp.Predict) -> str:
4011        model = self.sql(expression, "this")
4012        model = f"MODEL {model}"
4013        table = self.sql(expression, "expression")
4014        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4015        parameters = self.sql(expression, "params_struct")
4016        return self.func("PREDICT", model, table, parameters or None)
4017
4018    def forin_sql(self, expression: exp.ForIn) -> str:
4019        this = self.sql(expression, "this")
4020        expression_sql = self.sql(expression, "expression")
4021        return f"FOR {this} DO {expression_sql}"
4022
4023    def refresh_sql(self, expression: exp.Refresh) -> str:
4024        this = self.sql(expression, "this")
4025        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4026        return f"REFRESH {table}{this}"
4027
4028    def toarray_sql(self, expression: exp.ToArray) -> str:
4029        arg = expression.this
4030        if not arg.type:
4031            from sqlglot.optimizer.annotate_types import annotate_types
4032
4033            arg = annotate_types(arg, dialect=self.dialect)
4034
4035        if arg.is_type(exp.DataType.Type.ARRAY):
4036            return self.sql(arg)
4037
4038        cond_for_null = arg.is_(exp.null())
4039        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4040
4041    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4042        this = expression.this
4043        time_format = self.format_time(expression)
4044
4045        if time_format:
4046            return self.sql(
4047                exp.cast(
4048                    exp.StrToTime(this=this, format=expression.args["format"]),
4049                    exp.DataType.Type.TIME,
4050                )
4051            )
4052
4053        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4054            return self.sql(this)
4055
4056        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4057
4058    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4059        this = expression.this
4060        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4061            return self.sql(this)
4062
4063        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4064
4065    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4066        this = expression.this
4067        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4068            return self.sql(this)
4069
4070        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4071
4072    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4073        this = expression.this
4074        time_format = self.format_time(expression)
4075
4076        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4077            return self.sql(
4078                exp.cast(
4079                    exp.StrToTime(this=this, format=expression.args["format"]),
4080                    exp.DataType.Type.DATE,
4081                )
4082            )
4083
4084        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4085            return self.sql(this)
4086
4087        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4088
4089    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4090        return self.sql(
4091            exp.func(
4092                "DATEDIFF",
4093                expression.this,
4094                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4095                "day",
4096            )
4097        )
4098
4099    def lastday_sql(self, expression: exp.LastDay) -> str:
4100        if self.LAST_DAY_SUPPORTS_DATE_PART:
4101            return self.function_fallback_sql(expression)
4102
4103        unit = expression.text("unit")
4104        if unit and unit != "MONTH":
4105            self.unsupported("Date parts are not supported in LAST_DAY.")
4106
4107        return self.func("LAST_DAY", expression.this)
4108
4109    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4110        from sqlglot.dialects.dialect import unit_to_str
4111
4112        return self.func(
4113            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4114        )
4115
4116    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4117        if self.CAN_IMPLEMENT_ARRAY_ANY:
4118            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4119            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4120            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4121            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4122
4123        from sqlglot.dialects import Dialect
4124
4125        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4126        if self.dialect.__class__ != Dialect:
4127            self.unsupported("ARRAY_ANY is unsupported")
4128
4129        return self.function_fallback_sql(expression)
4130
4131    def struct_sql(self, expression: exp.Struct) -> str:
4132        expression.set(
4133            "expressions",
4134            [
4135                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4136                if isinstance(e, exp.PropertyEQ)
4137                else e
4138                for e in expression.expressions
4139            ],
4140        )
4141
4142        return self.function_fallback_sql(expression)
4143
4144    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4145        low = self.sql(expression, "this")
4146        high = self.sql(expression, "expression")
4147
4148        return f"{low} TO {high}"
4149
4150    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4151        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4152        tables = f" {self.expressions(expression)}"
4153
4154        exists = " IF EXISTS" if expression.args.get("exists") else ""
4155
4156        on_cluster = self.sql(expression, "cluster")
4157        on_cluster = f" {on_cluster}" if on_cluster else ""
4158
4159        identity = self.sql(expression, "identity")
4160        identity = f" {identity} IDENTITY" if identity else ""
4161
4162        option = self.sql(expression, "option")
4163        option = f" {option}" if option else ""
4164
4165        partition = self.sql(expression, "partition")
4166        partition = f" {partition}" if partition else ""
4167
4168        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4169
4170    # This transpiles T-SQL's CONVERT function
4171    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
4172    def convert_sql(self, expression: exp.Convert) -> str:
4173        to = expression.this
4174        value = expression.expression
4175        style = expression.args.get("style")
4176        safe = expression.args.get("safe")
4177        strict = expression.args.get("strict")
4178
4179        if not to or not value:
4180            return ""
4181
4182        # Retrieve length of datatype and override to default if not specified
4183        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4184            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4185
4186        transformed: t.Optional[exp.Expression] = None
4187        cast = exp.Cast if strict else exp.TryCast
4188
4189        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4190        if isinstance(style, exp.Literal) and style.is_int:
4191            from sqlglot.dialects.tsql import TSQL
4192
4193            style_value = style.name
4194            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4195            if not converted_style:
4196                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4197
4198            fmt = exp.Literal.string(converted_style)
4199
4200            if to.this == exp.DataType.Type.DATE:
4201                transformed = exp.StrToDate(this=value, format=fmt)
4202            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4203                transformed = exp.StrToTime(this=value, format=fmt)
4204            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4205                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4206            elif to.this == exp.DataType.Type.TEXT:
4207                transformed = exp.TimeToStr(this=value, format=fmt)
4208
4209        if not transformed:
4210            transformed = cast(this=value, to=to, safe=safe)
4211
4212        return self.sql(transformed)
4213
4214    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
4215        this = expression.this
4216        if isinstance(this, exp.JSONPathWildcard):
4217            this = self.json_path_part(this)
4218            return f".{this}" if this else ""
4219
4220        if exp.SAFE_IDENTIFIER_RE.match(this):
4221            return f".{this}"
4222
4223        this = self.json_path_part(this)
4224        return (
4225            f"[{this}]"
4226            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
4227            else f".{this}"
4228        )
4229
4230    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
4231        this = self.json_path_part(expression.this)
4232        return f"[{this}]" if this else ""
4233
4234    def _simplify_unless_literal(self, expression: E) -> E:
4235        if not isinstance(expression, exp.Literal):
4236            from sqlglot.optimizer.simplify import simplify
4237
4238            expression = simplify(expression, dialect=self.dialect)
4239
4240        return expression
4241
4242    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
4243        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
4244            # The first modifier here will be the one closest to the AggFunc's arg
4245            mods = sorted(
4246                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
4247                key=lambda x: 0
4248                if isinstance(x, exp.HavingMax)
4249                else (1 if isinstance(x, exp.Order) else 2),
4250            )
4251
4252            if mods:
4253                mod = mods[0]
4254                this = expression.__class__(this=mod.this.copy())
4255                this.meta["inline"] = True
4256                mod.this.replace(this)
4257                return self.sql(expression.this)
4258
4259            agg_func = expression.find(exp.AggFunc)
4260
4261            if agg_func:
4262                return self.sql(agg_func)[:-1] + f" {text})"
4263
4264        return f"{self.sql(expression, 'this')} {text}"
4265
4266    def _replace_line_breaks(self, string: str) -> str:
4267        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
4268        if self.pretty:
4269            return string.replace("\n", self.SENTINEL_LINE_BREAK)
4270        return string
4271
4272    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4273        option = self.sql(expression, "this")
4274
4275        if expression.expressions:
4276            upper = option.upper()
4277
4278            # Snowflake FILE_FORMAT options are separated by whitespace
4279            sep = " " if upper == "FILE_FORMAT" else ", "
4280
4281            # Databricks copy/format options do not set their list of values with EQ
4282            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4283            values = self.expressions(expression, flat=True, sep=sep)
4284            return f"{option}{op}({values})"
4285
4286        value = self.sql(expression, "expression")
4287
4288        if not value:
4289            return option
4290
4291        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4292
4293        return f"{option}{op}{value}"
4294
4295    def credentials_sql(self, expression: exp.Credentials) -> str:
4296        cred_expr = expression.args.get("credentials")
4297        if isinstance(cred_expr, exp.Literal):
4298            # Redshift case: CREDENTIALS <string>
4299            credentials = self.sql(expression, "credentials")
4300            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4301        else:
4302            # Snowflake case: CREDENTIALS = (...)
4303            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4304            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4305
4306        storage = self.sql(expression, "storage")
4307        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4308
4309        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4310        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4311
4312        iam_role = self.sql(expression, "iam_role")
4313        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4314
4315        region = self.sql(expression, "region")
4316        region = f" REGION {region}" if region else ""
4317
4318        return f"{credentials}{storage}{encryption}{iam_role}{region}"
4319
4320    def copy_sql(self, expression: exp.Copy) -> str:
4321        this = self.sql(expression, "this")
4322        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4323
4324        credentials = self.sql(expression, "credentials")
4325        credentials = self.seg(credentials) if credentials else ""
4326        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4327        files = self.expressions(expression, key="files", flat=True)
4328
4329        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4330        params = self.expressions(
4331            expression,
4332            key="params",
4333            sep=sep,
4334            new_line=True,
4335            skip_last=True,
4336            skip_first=True,
4337            indent=self.COPY_PARAMS_ARE_WRAPPED,
4338        )
4339
4340        if params:
4341            if self.COPY_PARAMS_ARE_WRAPPED:
4342                params = f" WITH ({params})"
4343            elif not self.pretty:
4344                params = f" {params}"
4345
4346        return f"COPY{this}{kind} {files}{credentials}{params}"
4347
4348    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4349        return ""
4350
4351    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4352        on_sql = "ON" if expression.args.get("on") else "OFF"
4353        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4354        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4355        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4356        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4357
4358        if filter_col or retention_period:
4359            on_sql = self.func("ON", filter_col, retention_period)
4360
4361        return f"DATA_DELETION={on_sql}"
4362
4363    def maskingpolicycolumnconstraint_sql(
4364        self, expression: exp.MaskingPolicyColumnConstraint
4365    ) -> str:
4366        this = self.sql(expression, "this")
4367        expressions = self.expressions(expression, flat=True)
4368        expressions = f" USING ({expressions})" if expressions else ""
4369        return f"MASKING POLICY {this}{expressions}"
4370
4371    def gapfill_sql(self, expression: exp.GapFill) -> str:
4372        this = self.sql(expression, "this")
4373        this = f"TABLE {this}"
4374        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
4375
4376    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4377        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
4378
4379    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4380        this = self.sql(expression, "this")
4381        expr = expression.expression
4382
4383        if isinstance(expr, exp.Func):
4384            # T-SQL's CLR functions are case sensitive
4385            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4386        else:
4387            expr = self.sql(expression, "expression")
4388
4389        return self.scope_resolution(expr, this)
4390
4391    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4392        if self.PARSE_JSON_NAME is None:
4393            return self.sql(expression.this)
4394
4395        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
4396
4397    def rand_sql(self, expression: exp.Rand) -> str:
4398        lower = self.sql(expression, "lower")
4399        upper = self.sql(expression, "upper")
4400
4401        if lower and upper:
4402            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4403        return self.func("RAND", expression.this)
4404
4405    def changes_sql(self, expression: exp.Changes) -> str:
4406        information = self.sql(expression, "information")
4407        information = f"INFORMATION => {information}"
4408        at_before = self.sql(expression, "at_before")
4409        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4410        end = self.sql(expression, "end")
4411        end = f"{self.seg('')}{end}" if end else ""
4412
4413        return f"CHANGES ({information}){at_before}{end}"
4414
4415    def pad_sql(self, expression: exp.Pad) -> str:
4416        prefix = "L" if expression.args.get("is_left") else "R"
4417
4418        fill_pattern = self.sql(expression, "fill_pattern") or None
4419        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4420            fill_pattern = "' '"
4421
4422        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
4423
4424    def summarize_sql(self, expression: exp.Summarize) -> str:
4425        table = " TABLE" if expression.args.get("table") else ""
4426        return f"SUMMARIZE{table} {self.sql(expression.this)}"
4427
4428    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4429        generate_series = exp.GenerateSeries(**expression.args)
4430
4431        parent = expression.parent
4432        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4433            parent = parent.parent
4434
4435        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4436            return self.sql(exp.Unnest(expressions=[generate_series]))
4437
4438        if isinstance(parent, exp.Select):
4439            self.unsupported("GenerateSeries projection unnesting is not supported.")
4440
4441        return self.sql(generate_series)
4442
4443    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4444        exprs = expression.expressions
4445        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4446            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4447        else:
4448            rhs = self.expressions(expression)
4449
4450        return self.func(name, expression.this, rhs or None)
4451
4452    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4453        if self.SUPPORTS_CONVERT_TIMEZONE:
4454            return self.function_fallback_sql(expression)
4455
4456        source_tz = expression.args.get("source_tz")
4457        target_tz = expression.args.get("target_tz")
4458        timestamp = expression.args.get("timestamp")
4459
4460        if source_tz and timestamp:
4461            timestamp = exp.AtTimeZone(
4462                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4463            )
4464
4465        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4466
4467        return self.sql(expr)
4468
4469    def json_sql(self, expression: exp.JSON) -> str:
4470        this = self.sql(expression, "this")
4471        this = f" {this}" if this else ""
4472
4473        _with = expression.args.get("with")
4474
4475        if _with is None:
4476            with_sql = ""
4477        elif not _with:
4478            with_sql = " WITHOUT"
4479        else:
4480            with_sql = " WITH"
4481
4482        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4483
4484        return f"JSON{this}{with_sql}{unique_sql}"
4485
4486    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4487        def _generate_on_options(arg: t.Any) -> str:
4488            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4489
4490        path = self.sql(expression, "path")
4491        returning = self.sql(expression, "returning")
4492        returning = f" RETURNING {returning}" if returning else ""
4493
4494        on_condition = self.sql(expression, "on_condition")
4495        on_condition = f" {on_condition}" if on_condition else ""
4496
4497        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4498
4499    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4500        else_ = "ELSE " if expression.args.get("else_") else ""
4501        condition = self.sql(expression, "expression")
4502        condition = f"WHEN {condition} THEN " if condition else else_
4503        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4504        return f"{condition}{insert}"
4505
4506    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4507        kind = self.sql(expression, "kind")
4508        expressions = self.seg(self.expressions(expression, sep=" "))
4509        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4510        return res
4511
4512    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4513        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4514        empty = expression.args.get("empty")
4515        empty = (
4516            f"DEFAULT {empty} ON EMPTY"
4517            if isinstance(empty, exp.Expression)
4518            else self.sql(expression, "empty")
4519        )
4520
4521        error = expression.args.get("error")
4522        error = (
4523            f"DEFAULT {error} ON ERROR"
4524            if isinstance(error, exp.Expression)
4525            else self.sql(expression, "error")
4526        )
4527
4528        if error and empty:
4529            error = (
4530                f"{empty} {error}"
4531                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4532                else f"{error} {empty}"
4533            )
4534            empty = ""
4535
4536        null = self.sql(expression, "null")
4537
4538        return f"{empty}{error}{null}"
4539
4540    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4541        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4542        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
4543
4544    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4545        this = self.sql(expression, "this")
4546        path = self.sql(expression, "path")
4547
4548        passing = self.expressions(expression, "passing")
4549        passing = f" PASSING {passing}" if passing else ""
4550
4551        on_condition = self.sql(expression, "on_condition")
4552        on_condition = f" {on_condition}" if on_condition else ""
4553
4554        path = f"{path}{passing}{on_condition}"
4555
4556        return self.func("JSON_EXISTS", this, path)
4557
4558    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4559        array_agg = self.function_fallback_sql(expression)
4560
4561        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4562        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4563        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4564            parent = expression.parent
4565            if isinstance(parent, exp.Filter):
4566                parent_cond = parent.expression.this
4567                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4568            else:
4569                this = expression.this
4570                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4571                if this.find(exp.Column):
4572                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4573                    this_sql = (
4574                        self.expressions(this)
4575                        if isinstance(this, exp.Distinct)
4576                        else self.sql(expression, "this")
4577                    )
4578
4579                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4580
4581        return array_agg
4582
4583    def apply_sql(self, expression: exp.Apply) -> str:
4584        this = self.sql(expression, "this")
4585        expr = self.sql(expression, "expression")
4586
4587        return f"{this} APPLY({expr})"
4588
4589    def grant_sql(self, expression: exp.Grant) -> str:
4590        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4591
4592        kind = self.sql(expression, "kind")
4593        kind = f" {kind}" if kind else ""
4594
4595        securable = self.sql(expression, "securable")
4596        securable = f" {securable}" if securable else ""
4597
4598        principals = self.expressions(expression, key="principals", flat=True)
4599
4600        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4601
4602        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4603
4604    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4605        this = self.sql(expression, "this")
4606        columns = self.expressions(expression, flat=True)
4607        columns = f"({columns})" if columns else ""
4608
4609        return f"{this}{columns}"
4610
4611    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4612        this = self.sql(expression, "this")
4613
4614        kind = self.sql(expression, "kind")
4615        kind = f"{kind} " if kind else ""
4616
4617        return f"{kind}{this}"
4618
4619    def columns_sql(self, expression: exp.Columns):
4620        func = self.function_fallback_sql(expression)
4621        if expression.args.get("unpack"):
4622            func = f"*{func}"
4623
4624        return func
4625
4626    def overlay_sql(self, expression: exp.Overlay):
4627        this = self.sql(expression, "this")
4628        expr = self.sql(expression, "expression")
4629        from_sql = self.sql(expression, "from")
4630        for_sql = self.sql(expression, "for")
4631        for_sql = f" FOR {for_sql}" if for_sql else ""
4632
4633        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
4634
4635    @unsupported_args("format")
4636    def todouble_sql(self, expression: exp.ToDouble) -> str:
4637        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
4638
4639    def string_sql(self, expression: exp.String) -> str:
4640        this = expression.this
4641        zone = expression.args.get("zone")
4642
4643        if zone:
4644            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4645            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4646            # set for source_tz to transpile the time conversion before the STRING cast
4647            this = exp.ConvertTimezone(
4648                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4649            )
4650
4651        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
4652
4653    def median_sql(self, expression: exp.Median):
4654        if not self.SUPPORTS_MEDIAN:
4655            return self.sql(
4656                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4657            )
4658
4659        return self.function_fallback_sql(expression)
4660
4661    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4662        filler = self.sql(expression, "this")
4663        filler = f" {filler}" if filler else ""
4664        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4665        return f"TRUNCATE{filler} {with_count}"
4666
4667    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4668        if self.SUPPORTS_UNIX_SECONDS:
4669            return self.function_fallback_sql(expression)
4670
4671        start_ts = exp.cast(
4672            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4673        )
4674
4675        return self.sql(
4676            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4677        )
4678
4679    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4680        dim = expression.expression
4681
4682        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4683        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4684            if not (dim.is_int and dim.name == "1"):
4685                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4686            dim = None
4687
4688        # If dimension is required but not specified, default initialize it
4689        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4690            dim = exp.Literal.number(1)
4691
4692        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4693
4694    def attach_sql(self, expression: exp.Attach) -> str:
4695        this = self.sql(expression, "this")
4696        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4697        expressions = self.expressions(expression)
4698        expressions = f" ({expressions})" if expressions else ""
4699
4700        return f"ATTACH{exists_sql} {this}{expressions}"
4701
4702    def detach_sql(self, expression: exp.Detach) -> str:
4703        this = self.sql(expression, "this")
4704        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4705
4706        return f"DETACH{exists_sql} {this}"
4707
4708    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4709        this = self.sql(expression, "this")
4710        value = self.sql(expression, "expression")
4711        value = f" {value}" if value else ""
4712        return f"{this}{value}"
4713
4714    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4715        this_sql = self.sql(expression, "this")
4716        if isinstance(expression.this, exp.Table):
4717            this_sql = f"TABLE {this_sql}"
4718
4719        return self.func(
4720            "FEATURES_AT_TIME",
4721            this_sql,
4722            expression.args.get("time"),
4723            expression.args.get("num_rows"),
4724            expression.args.get("ignore_feature_nulls"),
4725        )
4726
4727    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4728        return (
4729            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4730        )
4731
4732    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4733        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4734        encode = f"{encode} {self.sql(expression, 'this')}"
4735
4736        properties = expression.args.get("properties")
4737        if properties:
4738            encode = f"{encode} {self.properties(properties)}"
4739
4740        return encode
4741
4742    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4743        this = self.sql(expression, "this")
4744        include = f"INCLUDE {this}"
4745
4746        column_def = self.sql(expression, "column_def")
4747        if column_def:
4748            include = f"{include} {column_def}"
4749
4750        alias = self.sql(expression, "alias")
4751        if alias:
4752            include = f"{include} AS {alias}"
4753
4754        return include
4755
4756    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4757        name = f"NAME {self.sql(expression, 'this')}"
4758        return self.func("XMLELEMENT", name, *expression.expressions)
4759
4760    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4761        partitions = self.expressions(expression, "partition_expressions")
4762        create = self.expressions(expression, "create_expressions")
4763        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
4764
4765    def partitionbyrangepropertydynamic_sql(
4766        self, expression: exp.PartitionByRangePropertyDynamic
4767    ) -> str:
4768        start = self.sql(expression, "start")
4769        end = self.sql(expression, "end")
4770
4771        every = expression.args["every"]
4772        if isinstance(every, exp.Interval) and every.this.is_string:
4773            every.this.replace(exp.Literal.number(every.name))
4774
4775        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4776
4777    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4778        name = self.sql(expression, "this")
4779        values = self.expressions(expression, flat=True)
4780
4781        return f"NAME {name} VALUE {values}"
4782
4783    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4784        kind = self.sql(expression, "kind")
4785        sample = self.sql(expression, "sample")
4786        return f"SAMPLE {sample} {kind}"
4787
4788    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4789        kind = self.sql(expression, "kind")
4790        option = self.sql(expression, "option")
4791        option = f" {option}" if option else ""
4792        this = self.sql(expression, "this")
4793        this = f" {this}" if this else ""
4794        columns = self.expressions(expression)
4795        columns = f" {columns}" if columns else ""
4796        return f"{kind}{option} STATISTICS{this}{columns}"
4797
4798    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4799        this = self.sql(expression, "this")
4800        columns = self.expressions(expression)
4801        inner_expression = self.sql(expression, "expression")
4802        inner_expression = f" {inner_expression}" if inner_expression else ""
4803        update_options = self.sql(expression, "update_options")
4804        update_options = f" {update_options} UPDATE" if update_options else ""
4805        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
4806
4807    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4808        kind = self.sql(expression, "kind")
4809        kind = f" {kind}" if kind else ""
4810        return f"DELETE{kind} STATISTICS"
4811
4812    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4813        inner_expression = self.sql(expression, "expression")
4814        return f"LIST CHAINED ROWS{inner_expression}"
4815
4816    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4817        kind = self.sql(expression, "kind")
4818        this = self.sql(expression, "this")
4819        this = f" {this}" if this else ""
4820        inner_expression = self.sql(expression, "expression")
4821        return f"VALIDATE {kind}{this}{inner_expression}"
4822
4823    def analyze_sql(self, expression: exp.Analyze) -> str:
4824        options = self.expressions(expression, key="options", sep=" ")
4825        options = f" {options}" if options else ""
4826        kind = self.sql(expression, "kind")
4827        kind = f" {kind}" if kind else ""
4828        this = self.sql(expression, "this")
4829        this = f" {this}" if this else ""
4830        mode = self.sql(expression, "mode")
4831        mode = f" {mode}" if mode else ""
4832        properties = self.sql(expression, "properties")
4833        properties = f" {properties}" if properties else ""
4834        partition = self.sql(expression, "partition")
4835        partition = f" {partition}" if partition else ""
4836        inner_expression = self.sql(expression, "expression")
4837        inner_expression = f" {inner_expression}" if inner_expression else ""
4838        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4839
4840    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4841        this = self.sql(expression, "this")
4842        namespaces = self.expressions(expression, key="namespaces")
4843        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4844        passing = self.expressions(expression, key="passing")
4845        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4846        columns = self.expressions(expression, key="columns")
4847        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4848        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4849        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4850
4851    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4852        this = self.sql(expression, "this")
4853        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
4854
4855    def export_sql(self, expression: exp.Export) -> str:
4856        this = self.sql(expression, "this")
4857        connection = self.sql(expression, "connection")
4858        connection = f"WITH CONNECTION {connection} " if connection else ""
4859        options = self.sql(expression, "options")
4860        return f"EXPORT DATA {connection}{options} AS {this}"
4861
4862    def declare_sql(self, expression: exp.Declare) -> str:
4863        return f"DECLARE {self.expressions(expression, flat=True)}"
4864
4865    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4866        variable = self.sql(expression, "this")
4867        default = self.sql(expression, "default")
4868        default = f" = {default}" if default else ""
4869
4870        kind = self.sql(expression, "kind")
4871        if isinstance(expression.args.get("kind"), exp.Schema):
4872            kind = f"TABLE {kind}"
4873
4874        return f"{variable} AS {kind}{default}"
4875
4876    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4877        kind = self.sql(expression, "kind")
4878        this = self.sql(expression, "this")
4879        set = self.sql(expression, "expression")
4880        using = self.sql(expression, "using")
4881        using = f" USING {using}" if using else ""
4882
4883        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4884
4885        return f"{kind_sql} {this} SET {set}{using}"
4886
4887    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4888        params = self.expressions(expression, key="params", flat=True)
4889        return self.func(expression.name, *expression.expressions) + f"({params})"
4890
4891    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4892        return self.func(expression.name, *expression.expressions)
4893
4894    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4895        return self.anonymousaggfunc_sql(expression)
4896
4897    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4898        return self.parameterizedagg_sql(expression)
4899
4900    def show_sql(self, expression: exp.Show) -> str:
4901        self.unsupported("Unsupported SHOW statement")
4902        return ""
4903
4904    def put_sql(self, expression: exp.Put) -> str:
4905        props = expression.args.get("properties")
4906        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4907        this = self.sql(expression, "this")
4908        target = self.sql(expression, "target")
4909        return f"PUT {this} {target}{props_sql}"
logger = <Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE = re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
def unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
30def unsupported_args(
31    *args: t.Union[str, t.Tuple[str, str]],
32) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
33    """
34    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
35    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
36    """
37    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
38    for arg in args:
39        if isinstance(arg, str):
40            diagnostic_by_arg[arg] = None
41        else:
42            diagnostic_by_arg[arg[0]] = arg[1]
43
44    def decorator(func: GeneratorMethod) -> GeneratorMethod:
45        @wraps(func)
46        def _func(generator: G, expression: E) -> str:
47            expression_name = expression.__class__.__name__
48            dialect_name = generator.dialect.__class__.__name__
49
50            for arg_name, diagnostic in diagnostic_by_arg.items():
51                if expression.args.get(arg_name):
52                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
53                        arg_name, expression_name, dialect_name
54                    )
55                    generator.unsupported(diagnostic)
56
57            return func(generator, expression)
58
59        return _func
60
61    return decorator

Decorator that can be used to mark certain args of an Expression subclass as unsupported. It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).

class Generator:
  75class Generator(metaclass=_Generator):
  76    """
  77    Generator converts a given syntax tree to the corresponding SQL string.
  78
  79    Args:
  80        pretty: Whether to format the produced SQL string.
  81            Default: False.
  82        identify: Determines when an identifier should be quoted. Possible values are:
  83            False (default): Never quote, except in cases where it's mandatory by the dialect.
  84            True or 'always': Always quote.
  85            'safe': Only quote identifiers that are case insensitive.
  86        normalize: Whether to normalize identifiers to lowercase.
  87            Default: False.
  88        pad: The pad size in a formatted string. For example, this affects the indentation of
  89            a projection in a query, relative to its nesting level.
  90            Default: 2.
  91        indent: The indentation size in a formatted string. For example, this affects the
  92            indentation of subqueries and filters under a `WHERE` clause.
  93            Default: 2.
  94        normalize_functions: How to normalize function names. Possible values are:
  95            "upper" or True (default): Convert names to uppercase.
  96            "lower": Convert names to lowercase.
  97            False: Disables function name normalization.
  98        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
  99            Default ErrorLevel.WARN.
 100        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
 101            This is only relevant if unsupported_level is ErrorLevel.RAISE.
 102            Default: 3
 103        leading_comma: Whether the comma is leading or trailing in select expressions.
 104            This is only relevant when generating in pretty mode.
 105            Default: False
 106        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
 107            The default is on the smaller end because the length only represents a segment and not the true
 108            line length.
 109            Default: 80
 110        comments: Whether to preserve comments in the output SQL code.
 111            Default: True
 112    """
 113
 114    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
 115        **JSON_PATH_PART_TRANSFORMS,
 116        exp.AllowedValuesProperty: lambda self,
 117        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
 118        exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"),
 119        exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "),
 120        exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"),
 121        exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
 122        exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}",
 123        exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}",
 124        exp.CaseSpecificColumnConstraint: lambda _,
 125        e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
 126        exp.Ceil: lambda self, e: self.ceil_floor(e),
 127        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
 128        exp.CharacterSetProperty: lambda self,
 129        e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
 130        exp.ClusteredColumnConstraint: lambda self,
 131        e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})",
 132        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
 133        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
 134        exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}",
 135        exp.CopyGrantsProperty: lambda *_: "COPY GRANTS",
 136        exp.CredentialsProperty: lambda self,
 137        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
 138        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
 139        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
 140        exp.DynamicProperty: lambda *_: "DYNAMIC",
 141        exp.EmptyProperty: lambda *_: "EMPTY",
 142        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
 143        exp.EphemeralColumnConstraint: lambda self,
 144        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
 145        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
 146        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
 147        exp.Except: lambda self, e: self.set_operations(e),
 148        exp.ExternalProperty: lambda *_: "EXTERNAL",
 149        exp.Floor: lambda self, e: self.ceil_floor(e),
 150        exp.GlobalProperty: lambda *_: "GLOBAL",
 151        exp.HeapProperty: lambda *_: "HEAP",
 152        exp.IcebergProperty: lambda *_: "ICEBERG",
 153        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
 154        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
 155        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
 156        exp.Intersect: lambda self, e: self.set_operations(e),
 157        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
 158        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
 159        exp.LanguageProperty: lambda self, e: self.naked_property(e),
 160        exp.LocationProperty: lambda self, e: self.naked_property(e),
 161        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
 162        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
 163        exp.NonClusteredColumnConstraint: lambda self,
 164        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
 165        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
 166        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
 167        exp.OnCommitProperty: lambda _,
 168        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
 169        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
 170        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
 171        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
 172        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
 173        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
 174        exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression),
 175        exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression),
 176        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
 177        exp.ProjectionPolicyColumnConstraint: lambda self,
 178        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
 179        exp.RemoteWithConnectionModelProperty: lambda self,
 180        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
 181        exp.ReturnsProperty: lambda self, e: (
 182            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
 183        ),
 184        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
 185        exp.SecureProperty: lambda *_: "SECURE",
 186        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
 187        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
 188        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
 189        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
 190        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
 191        exp.SqlReadWriteProperty: lambda _, e: e.name,
 192        exp.SqlSecurityProperty: lambda _,
 193        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
 194        exp.StabilityProperty: lambda _, e: e.name,
 195        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
 196        exp.StreamingTableProperty: lambda *_: "STREAMING",
 197        exp.StrictProperty: lambda *_: "STRICT",
 198        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
 199        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
 200        exp.TemporaryProperty: lambda *_: "TEMPORARY",
 201        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
 202        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
 203        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
 204        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
 205        exp.TransientProperty: lambda *_: "TRANSIENT",
 206        exp.Union: lambda self, e: self.set_operations(e),
 207        exp.UnloggedProperty: lambda *_: "UNLOGGED",
 208        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
 209        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
 210        exp.Uuid: lambda *_: "UUID()",
 211        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
 212        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
 213        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
 214        exp.VolatileProperty: lambda *_: "VOLATILE",
 215        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
 216        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
 217        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
 218        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
 219        exp.ForceProperty: lambda *_: "FORCE",
 220    }
 221
 222    # Whether null ordering is supported in order by
 223    # True: Full Support, None: No support, False: No support for certain cases
 224    # such as window specifications, aggregate functions etc
 225    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
 226
 227    # Whether ignore nulls is inside the agg or outside.
 228    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
 229    IGNORE_NULLS_IN_FUNC = False
 230
 231    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
 232    LOCKING_READS_SUPPORTED = False
 233
 234    # Whether the EXCEPT and INTERSECT operations can return duplicates
 235    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
 236
 237    # Wrap derived values in parens, usually standard but spark doesn't support it
 238    WRAP_DERIVED_VALUES = True
 239
 240    # Whether create function uses an AS before the RETURN
 241    CREATE_FUNCTION_RETURN_AS = True
 242
 243    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
 244    MATCHED_BY_SOURCE = True
 245
 246    # Whether the INTERVAL expression works only with values like '1 day'
 247    SINGLE_STRING_INTERVAL = False
 248
 249    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
 250    INTERVAL_ALLOWS_PLURAL_FORM = True
 251
 252    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
 253    LIMIT_FETCH = "ALL"
 254
 255    # Whether limit and fetch allows expresions or just limits
 256    LIMIT_ONLY_LITERALS = False
 257
 258    # Whether a table is allowed to be renamed with a db
 259    RENAME_TABLE_WITH_DB = True
 260
 261    # The separator for grouping sets and rollups
 262    GROUPINGS_SEP = ","
 263
 264    # The string used for creating an index on a table
 265    INDEX_ON = "ON"
 266
 267    # Whether join hints should be generated
 268    JOIN_HINTS = True
 269
 270    # Whether table hints should be generated
 271    TABLE_HINTS = True
 272
 273    # Whether query hints should be generated
 274    QUERY_HINTS = True
 275
 276    # What kind of separator to use for query hints
 277    QUERY_HINT_SEP = ", "
 278
 279    # Whether comparing against booleans (e.g. x IS TRUE) is supported
 280    IS_BOOL_ALLOWED = True
 281
 282    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
 283    DUPLICATE_KEY_UPDATE_WITH_SET = True
 284
 285    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
 286    LIMIT_IS_TOP = False
 287
 288    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
 289    RETURNING_END = True
 290
 291    # Whether to generate an unquoted value for EXTRACT's date part argument
 292    EXTRACT_ALLOWS_QUOTES = True
 293
 294    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
 295    TZ_TO_WITH_TIME_ZONE = False
 296
 297    # Whether the NVL2 function is supported
 298    NVL2_SUPPORTED = True
 299
 300    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
 301    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
 302
 303    # Whether VALUES statements can be used as derived tables.
 304    # MySQL 5 and Redshift do not allow this, so when False, it will convert
 305    # SELECT * VALUES into SELECT UNION
 306    VALUES_AS_TABLE = True
 307
 308    # Whether the word COLUMN is included when adding a column with ALTER TABLE
 309    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
 310
 311    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
 312    UNNEST_WITH_ORDINALITY = True
 313
 314    # Whether FILTER (WHERE cond) can be used for conditional aggregation
 315    AGGREGATE_FILTER_SUPPORTED = True
 316
 317    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
 318    SEMI_ANTI_JOIN_WITH_SIDE = True
 319
 320    # Whether to include the type of a computed column in the CREATE DDL
 321    COMPUTED_COLUMN_WITH_TYPE = True
 322
 323    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
 324    SUPPORTS_TABLE_COPY = True
 325
 326    # Whether parentheses are required around the table sample's expression
 327    TABLESAMPLE_REQUIRES_PARENS = True
 328
 329    # Whether a table sample clause's size needs to be followed by the ROWS keyword
 330    TABLESAMPLE_SIZE_IS_ROWS = True
 331
 332    # The keyword(s) to use when generating a sample clause
 333    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
 334
 335    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
 336    TABLESAMPLE_WITH_METHOD = True
 337
 338    # The keyword to use when specifying the seed of a sample clause
 339    TABLESAMPLE_SEED_KEYWORD = "SEED"
 340
 341    # Whether COLLATE is a function instead of a binary operator
 342    COLLATE_IS_FUNC = False
 343
 344    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
 345    DATA_TYPE_SPECIFIERS_ALLOWED = False
 346
 347    # Whether conditions require booleans WHERE x = 0 vs WHERE x
 348    ENSURE_BOOLS = False
 349
 350    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
 351    CTE_RECURSIVE_KEYWORD_REQUIRED = True
 352
 353    # Whether CONCAT requires >1 arguments
 354    SUPPORTS_SINGLE_ARG_CONCAT = True
 355
 356    # Whether LAST_DAY function supports a date part argument
 357    LAST_DAY_SUPPORTS_DATE_PART = True
 358
 359    # Whether named columns are allowed in table aliases
 360    SUPPORTS_TABLE_ALIAS_COLUMNS = True
 361
 362    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
 363    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
 364
 365    # What delimiter to use for separating JSON key/value pairs
 366    JSON_KEY_VALUE_PAIR_SEP = ":"
 367
 368    # INSERT OVERWRITE TABLE x override
 369    INSERT_OVERWRITE = " OVERWRITE TABLE"
 370
 371    # Whether the SELECT .. INTO syntax is used instead of CTAS
 372    SUPPORTS_SELECT_INTO = False
 373
 374    # Whether UNLOGGED tables can be created
 375    SUPPORTS_UNLOGGED_TABLES = False
 376
 377    # Whether the CREATE TABLE LIKE statement is supported
 378    SUPPORTS_CREATE_TABLE_LIKE = True
 379
 380    # Whether the LikeProperty needs to be specified inside of the schema clause
 381    LIKE_PROPERTY_INSIDE_SCHEMA = False
 382
 383    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
 384    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
 385    MULTI_ARG_DISTINCT = True
 386
 387    # Whether the JSON extraction operators expect a value of type JSON
 388    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
 389
 390    # Whether bracketed keys like ["foo"] are supported in JSON paths
 391    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
 392
 393    # Whether to escape keys using single quotes in JSON paths
 394    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
 395
 396    # The JSONPathPart expressions supported by this dialect
 397    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
 398
 399    # Whether any(f(x) for x in array) can be implemented by this dialect
 400    CAN_IMPLEMENT_ARRAY_ANY = False
 401
 402    # Whether the function TO_NUMBER is supported
 403    SUPPORTS_TO_NUMBER = True
 404
 405    # Whether or not set op modifiers apply to the outer set op or select.
 406    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
 407    # True means limit 1 happens after the set op, False means it it happens on y.
 408    SET_OP_MODIFIERS = True
 409
 410    # Whether parameters from COPY statement are wrapped in parentheses
 411    COPY_PARAMS_ARE_WRAPPED = True
 412
 413    # Whether values of params are set with "=" token or empty space
 414    COPY_PARAMS_EQ_REQUIRED = False
 415
 416    # Whether COPY statement has INTO keyword
 417    COPY_HAS_INTO_KEYWORD = True
 418
 419    # Whether the conditional TRY(expression) function is supported
 420    TRY_SUPPORTED = True
 421
 422    # Whether the UESCAPE syntax in unicode strings is supported
 423    SUPPORTS_UESCAPE = True
 424
 425    # The keyword to use when generating a star projection with excluded columns
 426    STAR_EXCEPT = "EXCEPT"
 427
 428    # The HEX function name
 429    HEX_FUNC = "HEX"
 430
 431    # The keywords to use when prefixing & separating WITH based properties
 432    WITH_PROPERTIES_PREFIX = "WITH"
 433
 434    # Whether to quote the generated expression of exp.JsonPath
 435    QUOTE_JSON_PATH = True
 436
 437    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
 438    PAD_FILL_PATTERN_IS_REQUIRED = False
 439
 440    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
 441    SUPPORTS_EXPLODING_PROJECTIONS = True
 442
 443    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
 444    ARRAY_CONCAT_IS_VAR_LEN = True
 445
 446    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
 447    SUPPORTS_CONVERT_TIMEZONE = False
 448
 449    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
 450    SUPPORTS_MEDIAN = True
 451
 452    # Whether UNIX_SECONDS(timestamp) is supported
 453    SUPPORTS_UNIX_SECONDS = False
 454
 455    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
 456    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
 457
 458    # The function name of the exp.ArraySize expression
 459    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
 460
 461    # The syntax to use when altering the type of a column
 462    ALTER_SET_TYPE = "SET DATA TYPE"
 463
 464    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
 465    # None -> Doesn't support it at all
 466    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
 467    # True (Postgres) -> Explicitly requires it
 468    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
 469
 470    TYPE_MAPPING = {
 471        exp.DataType.Type.DATETIME2: "TIMESTAMP",
 472        exp.DataType.Type.NCHAR: "CHAR",
 473        exp.DataType.Type.NVARCHAR: "VARCHAR",
 474        exp.DataType.Type.MEDIUMTEXT: "TEXT",
 475        exp.DataType.Type.LONGTEXT: "TEXT",
 476        exp.DataType.Type.TINYTEXT: "TEXT",
 477        exp.DataType.Type.BLOB: "VARBINARY",
 478        exp.DataType.Type.MEDIUMBLOB: "BLOB",
 479        exp.DataType.Type.LONGBLOB: "BLOB",
 480        exp.DataType.Type.TINYBLOB: "BLOB",
 481        exp.DataType.Type.INET: "INET",
 482        exp.DataType.Type.ROWVERSION: "VARBINARY",
 483        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
 484    }
 485
 486    TIME_PART_SINGULARS = {
 487        "MICROSECONDS": "MICROSECOND",
 488        "SECONDS": "SECOND",
 489        "MINUTES": "MINUTE",
 490        "HOURS": "HOUR",
 491        "DAYS": "DAY",
 492        "WEEKS": "WEEK",
 493        "MONTHS": "MONTH",
 494        "QUARTERS": "QUARTER",
 495        "YEARS": "YEAR",
 496    }
 497
 498    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 499        "cluster": lambda self, e: self.sql(e, "cluster"),
 500        "distribute": lambda self, e: self.sql(e, "distribute"),
 501        "sort": lambda self, e: self.sql(e, "sort"),
 502        "windows": lambda self, e: (
 503            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
 504            if e.args.get("windows")
 505            else ""
 506        ),
 507        "qualify": lambda self, e: self.sql(e, "qualify"),
 508    }
 509
 510    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
 511
 512    STRUCT_DELIMITER = ("<", ">")
 513
 514    PARAMETER_TOKEN = "@"
 515    NAMED_PLACEHOLDER_TOKEN = ":"
 516
 517    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
 518
 519    PROPERTIES_LOCATION = {
 520        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
 521        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
 522        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
 523        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
 524        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
 525        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
 526        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
 527        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
 528        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
 529        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
 530        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
 531        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
 532        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
 533        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
 534        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
 535        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
 536        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
 537        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
 538        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
 539        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
 540        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 541        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 542        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
 543        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
 544        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
 545        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
 546        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
 547        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
 548        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
 549        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
 550        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
 551        exp.HeapProperty: exp.Properties.Location.POST_WITH,
 552        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
 553        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
 554        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
 555        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
 556        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
 557        exp.JournalProperty: exp.Properties.Location.POST_NAME,
 558        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
 559        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
 560        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
 561        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
 562        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
 563        exp.LogProperty: exp.Properties.Location.POST_NAME,
 564        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
 565        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
 566        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
 567        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
 568        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
 569        exp.Order: exp.Properties.Location.POST_SCHEMA,
 570        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
 571        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
 572        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
 573        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
 574        exp.Property: exp.Properties.Location.POST_WITH,
 575        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
 576        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
 577        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
 578        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
 579        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
 580        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
 581        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
 582        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
 583        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
 584        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
 585        exp.Set: exp.Properties.Location.POST_SCHEMA,
 586        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
 587        exp.SetProperty: exp.Properties.Location.POST_CREATE,
 588        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
 589        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
 590        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
 591        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 592        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
 593        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
 594        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
 595        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
 596        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
 597        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
 598        exp.Tags: exp.Properties.Location.POST_WITH,
 599        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
 600        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
 601        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
 602        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
 603        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
 604        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
 605        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
 606        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
 607        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
 608        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
 609        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
 610        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
 611        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
 612        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
 613        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
 614    }
 615
 616    # Keywords that can't be used as unquoted identifier names
 617    RESERVED_KEYWORDS: t.Set[str] = set()
 618
 619    # Expressions whose comments are separated from them for better formatting
 620    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 621        exp.Command,
 622        exp.Create,
 623        exp.Describe,
 624        exp.Delete,
 625        exp.Drop,
 626        exp.From,
 627        exp.Insert,
 628        exp.Join,
 629        exp.MultitableInserts,
 630        exp.Select,
 631        exp.SetOperation,
 632        exp.Update,
 633        exp.Where,
 634        exp.With,
 635    )
 636
 637    # Expressions that should not have their comments generated in maybe_comment
 638    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 639        exp.Binary,
 640        exp.SetOperation,
 641    )
 642
 643    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
 644    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
 645        exp.Column,
 646        exp.Literal,
 647        exp.Neg,
 648        exp.Paren,
 649    )
 650
 651    PARAMETERIZABLE_TEXT_TYPES = {
 652        exp.DataType.Type.NVARCHAR,
 653        exp.DataType.Type.VARCHAR,
 654        exp.DataType.Type.CHAR,
 655        exp.DataType.Type.NCHAR,
 656    }
 657
 658    # Expressions that need to have all CTEs under them bubbled up to them
 659    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
 660
 661    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
 662
 663    __slots__ = (
 664        "pretty",
 665        "identify",
 666        "normalize",
 667        "pad",
 668        "_indent",
 669        "normalize_functions",
 670        "unsupported_level",
 671        "max_unsupported",
 672        "leading_comma",
 673        "max_text_width",
 674        "comments",
 675        "dialect",
 676        "unsupported_messages",
 677        "_escaped_quote_end",
 678        "_escaped_identifier_end",
 679        "_next_name",
 680        "_identifier_start",
 681        "_identifier_end",
 682        "_quote_json_path_key_using_brackets",
 683    )
 684
 685    def __init__(
 686        self,
 687        pretty: t.Optional[bool] = None,
 688        identify: str | bool = False,
 689        normalize: bool = False,
 690        pad: int = 2,
 691        indent: int = 2,
 692        normalize_functions: t.Optional[str | bool] = None,
 693        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 694        max_unsupported: int = 3,
 695        leading_comma: bool = False,
 696        max_text_width: int = 80,
 697        comments: bool = True,
 698        dialect: DialectType = None,
 699    ):
 700        import sqlglot
 701        from sqlglot.dialects import Dialect
 702
 703        self.pretty = pretty if pretty is not None else sqlglot.pretty
 704        self.identify = identify
 705        self.normalize = normalize
 706        self.pad = pad
 707        self._indent = indent
 708        self.unsupported_level = unsupported_level
 709        self.max_unsupported = max_unsupported
 710        self.leading_comma = leading_comma
 711        self.max_text_width = max_text_width
 712        self.comments = comments
 713        self.dialect = Dialect.get_or_raise(dialect)
 714
 715        # This is both a Dialect property and a Generator argument, so we prioritize the latter
 716        self.normalize_functions = (
 717            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
 718        )
 719
 720        self.unsupported_messages: t.List[str] = []
 721        self._escaped_quote_end: str = (
 722            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
 723        )
 724        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
 725
 726        self._next_name = name_sequence("_t")
 727
 728        self._identifier_start = self.dialect.IDENTIFIER_START
 729        self._identifier_end = self.dialect.IDENTIFIER_END
 730
 731        self._quote_json_path_key_using_brackets = True
 732
 733    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
 734        """
 735        Generates the SQL string corresponding to the given syntax tree.
 736
 737        Args:
 738            expression: The syntax tree.
 739            copy: Whether to copy the expression. The generator performs mutations so
 740                it is safer to copy.
 741
 742        Returns:
 743            The SQL string corresponding to `expression`.
 744        """
 745        if copy:
 746            expression = expression.copy()
 747
 748        expression = self.preprocess(expression)
 749
 750        self.unsupported_messages = []
 751        sql = self.sql(expression).strip()
 752
 753        if self.pretty:
 754            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
 755
 756        if self.unsupported_level == ErrorLevel.IGNORE:
 757            return sql
 758
 759        if self.unsupported_level == ErrorLevel.WARN:
 760            for msg in self.unsupported_messages:
 761                logger.warning(msg)
 762        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
 763            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
 764
 765        return sql
 766
 767    def preprocess(self, expression: exp.Expression) -> exp.Expression:
 768        """Apply generic preprocessing transformations to a given expression."""
 769        expression = self._move_ctes_to_top_level(expression)
 770
 771        if self.ENSURE_BOOLS:
 772            from sqlglot.transforms import ensure_bools
 773
 774            expression = ensure_bools(expression)
 775
 776        return expression
 777
 778    def _move_ctes_to_top_level(self, expression: E) -> E:
 779        if (
 780            not expression.parent
 781            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
 782            and any(node.parent is not expression for node in expression.find_all(exp.With))
 783        ):
 784            from sqlglot.transforms import move_ctes_to_top_level
 785
 786            expression = move_ctes_to_top_level(expression)
 787        return expression
 788
 789    def unsupported(self, message: str) -> None:
 790        if self.unsupported_level == ErrorLevel.IMMEDIATE:
 791            raise UnsupportedError(message)
 792        self.unsupported_messages.append(message)
 793
 794    def sep(self, sep: str = " ") -> str:
 795        return f"{sep.strip()}\n" if self.pretty else sep
 796
 797    def seg(self, sql: str, sep: str = " ") -> str:
 798        return f"{self.sep(sep)}{sql}"
 799
 800    def pad_comment(self, comment: str) -> str:
 801        comment = " " + comment if comment[0].strip() else comment
 802        comment = comment + " " if comment[-1].strip() else comment
 803        return comment
 804
 805    def maybe_comment(
 806        self,
 807        sql: str,
 808        expression: t.Optional[exp.Expression] = None,
 809        comments: t.Optional[t.List[str]] = None,
 810        separated: bool = False,
 811    ) -> str:
 812        comments = (
 813            ((expression and expression.comments) if comments is None else comments)  # type: ignore
 814            if self.comments
 815            else None
 816        )
 817
 818        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
 819            return sql
 820
 821        comments_sql = " ".join(
 822            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
 823        )
 824
 825        if not comments_sql:
 826            return sql
 827
 828        comments_sql = self._replace_line_breaks(comments_sql)
 829
 830        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
 831            return (
 832                f"{self.sep()}{comments_sql}{sql}"
 833                if not sql or sql[0].isspace()
 834                else f"{comments_sql}{self.sep()}{sql}"
 835            )
 836
 837        return f"{sql} {comments_sql}"
 838
 839    def wrap(self, expression: exp.Expression | str) -> str:
 840        this_sql = (
 841            self.sql(expression)
 842            if isinstance(expression, exp.UNWRAPPED_QUERIES)
 843            else self.sql(expression, "this")
 844        )
 845        if not this_sql:
 846            return "()"
 847
 848        this_sql = self.indent(this_sql, level=1, pad=0)
 849        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
 850
 851    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
 852        original = self.identify
 853        self.identify = False
 854        result = func(*args, **kwargs)
 855        self.identify = original
 856        return result
 857
 858    def normalize_func(self, name: str) -> str:
 859        if self.normalize_functions == "upper" or self.normalize_functions is True:
 860            return name.upper()
 861        if self.normalize_functions == "lower":
 862            return name.lower()
 863        return name
 864
 865    def indent(
 866        self,
 867        sql: str,
 868        level: int = 0,
 869        pad: t.Optional[int] = None,
 870        skip_first: bool = False,
 871        skip_last: bool = False,
 872    ) -> str:
 873        if not self.pretty or not sql:
 874            return sql
 875
 876        pad = self.pad if pad is None else pad
 877        lines = sql.split("\n")
 878
 879        return "\n".join(
 880            (
 881                line
 882                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
 883                else f"{' ' * (level * self._indent + pad)}{line}"
 884            )
 885            for i, line in enumerate(lines)
 886        )
 887
 888    def sql(
 889        self,
 890        expression: t.Optional[str | exp.Expression],
 891        key: t.Optional[str] = None,
 892        comment: bool = True,
 893    ) -> str:
 894        if not expression:
 895            return ""
 896
 897        if isinstance(expression, str):
 898            return expression
 899
 900        if key:
 901            value = expression.args.get(key)
 902            if value:
 903                return self.sql(value)
 904            return ""
 905
 906        transform = self.TRANSFORMS.get(expression.__class__)
 907
 908        if callable(transform):
 909            sql = transform(self, expression)
 910        elif isinstance(expression, exp.Expression):
 911            exp_handler_name = f"{expression.key}_sql"
 912
 913            if hasattr(self, exp_handler_name):
 914                sql = getattr(self, exp_handler_name)(expression)
 915            elif isinstance(expression, exp.Func):
 916                sql = self.function_fallback_sql(expression)
 917            elif isinstance(expression, exp.Property):
 918                sql = self.property_sql(expression)
 919            else:
 920                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
 921        else:
 922            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
 923
 924        return self.maybe_comment(sql, expression) if self.comments and comment else sql
 925
 926    def uncache_sql(self, expression: exp.Uncache) -> str:
 927        table = self.sql(expression, "this")
 928        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
 929        return f"UNCACHE TABLE{exists_sql} {table}"
 930
 931    def cache_sql(self, expression: exp.Cache) -> str:
 932        lazy = " LAZY" if expression.args.get("lazy") else ""
 933        table = self.sql(expression, "this")
 934        options = expression.args.get("options")
 935        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
 936        sql = self.sql(expression, "expression")
 937        sql = f" AS{self.sep()}{sql}" if sql else ""
 938        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
 939        return self.prepend_ctes(expression, sql)
 940
 941    def characterset_sql(self, expression: exp.CharacterSet) -> str:
 942        if isinstance(expression.parent, exp.Cast):
 943            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
 944        default = "DEFAULT " if expression.args.get("default") else ""
 945        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
 946
 947    def column_parts(self, expression: exp.Column) -> str:
 948        return ".".join(
 949            self.sql(part)
 950            for part in (
 951                expression.args.get("catalog"),
 952                expression.args.get("db"),
 953                expression.args.get("table"),
 954                expression.args.get("this"),
 955            )
 956            if part
 957        )
 958
 959    def column_sql(self, expression: exp.Column) -> str:
 960        join_mark = " (+)" if expression.args.get("join_mark") else ""
 961
 962        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
 963            join_mark = ""
 964            self.unsupported("Outer join syntax using the (+) operator is not supported.")
 965
 966        return f"{self.column_parts(expression)}{join_mark}"
 967
 968    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
 969        this = self.sql(expression, "this")
 970        this = f" {this}" if this else ""
 971        position = self.sql(expression, "position")
 972        return f"{position}{this}"
 973
 974    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
 975        column = self.sql(expression, "this")
 976        kind = self.sql(expression, "kind")
 977        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
 978        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
 979        kind = f"{sep}{kind}" if kind else ""
 980        constraints = f" {constraints}" if constraints else ""
 981        position = self.sql(expression, "position")
 982        position = f" {position}" if position else ""
 983
 984        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
 985            kind = ""
 986
 987        return f"{exists}{column}{kind}{constraints}{position}"
 988
 989    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
 990        this = self.sql(expression, "this")
 991        kind_sql = self.sql(expression, "kind").strip()
 992        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
 993
 994    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
 995        this = self.sql(expression, "this")
 996        if expression.args.get("not_null"):
 997            persisted = " PERSISTED NOT NULL"
 998        elif expression.args.get("persisted"):
 999            persisted = " PERSISTED"
1000        else:
1001            persisted = ""
1002        return f"AS {this}{persisted}"
1003
1004    def autoincrementcolumnconstraint_sql(self, _) -> str:
1005        return self.token_sql(TokenType.AUTO_INCREMENT)
1006
1007    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1008        if isinstance(expression.this, list):
1009            this = self.wrap(self.expressions(expression, key="this", flat=True))
1010        else:
1011            this = self.sql(expression, "this")
1012
1013        return f"COMPRESS {this}"
1014
1015    def generatedasidentitycolumnconstraint_sql(
1016        self, expression: exp.GeneratedAsIdentityColumnConstraint
1017    ) -> str:
1018        this = ""
1019        if expression.this is not None:
1020            on_null = " ON NULL" if expression.args.get("on_null") else ""
1021            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1022
1023        start = expression.args.get("start")
1024        start = f"START WITH {start}" if start else ""
1025        increment = expression.args.get("increment")
1026        increment = f" INCREMENT BY {increment}" if increment else ""
1027        minvalue = expression.args.get("minvalue")
1028        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1029        maxvalue = expression.args.get("maxvalue")
1030        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1031        cycle = expression.args.get("cycle")
1032        cycle_sql = ""
1033
1034        if cycle is not None:
1035            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1036            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1037
1038        sequence_opts = ""
1039        if start or increment or cycle_sql:
1040            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1041            sequence_opts = f" ({sequence_opts.strip()})"
1042
1043        expr = self.sql(expression, "expression")
1044        expr = f"({expr})" if expr else "IDENTITY"
1045
1046        return f"GENERATED{this} AS {expr}{sequence_opts}"
1047
1048    def generatedasrowcolumnconstraint_sql(
1049        self, expression: exp.GeneratedAsRowColumnConstraint
1050    ) -> str:
1051        start = "START" if expression.args.get("start") else "END"
1052        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1053        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
1054
1055    def periodforsystemtimeconstraint_sql(
1056        self, expression: exp.PeriodForSystemTimeConstraint
1057    ) -> str:
1058        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
1059
1060    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1061        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
1062
1063    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
1064        return f"AS {self.sql(expression, 'this')}"
1065
1066    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1067        desc = expression.args.get("desc")
1068        if desc is not None:
1069            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1070        options = self.expressions(expression, key="options", flat=True, sep=" ")
1071        options = f" {options}" if options else ""
1072        return f"PRIMARY KEY{options}"
1073
1074    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1075        this = self.sql(expression, "this")
1076        this = f" {this}" if this else ""
1077        index_type = expression.args.get("index_type")
1078        index_type = f" USING {index_type}" if index_type else ""
1079        on_conflict = self.sql(expression, "on_conflict")
1080        on_conflict = f" {on_conflict}" if on_conflict else ""
1081        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1082        options = self.expressions(expression, key="options", flat=True, sep=" ")
1083        options = f" {options}" if options else ""
1084        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
1085
1086    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1087        return self.sql(expression, "this")
1088
1089    def create_sql(self, expression: exp.Create) -> str:
1090        kind = self.sql(expression, "kind")
1091        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1092        properties = expression.args.get("properties")
1093        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1094
1095        this = self.createable_sql(expression, properties_locs)
1096
1097        properties_sql = ""
1098        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1099            exp.Properties.Location.POST_WITH
1100        ):
1101            properties_sql = self.sql(
1102                exp.Properties(
1103                    expressions=[
1104                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1105                        *properties_locs[exp.Properties.Location.POST_WITH],
1106                    ]
1107                )
1108            )
1109
1110            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1111                properties_sql = self.sep() + properties_sql
1112            elif not self.pretty:
1113                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1114                properties_sql = f" {properties_sql}"
1115
1116        begin = " BEGIN" if expression.args.get("begin") else ""
1117        end = " END" if expression.args.get("end") else ""
1118
1119        expression_sql = self.sql(expression, "expression")
1120        if expression_sql:
1121            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1122
1123            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1124                postalias_props_sql = ""
1125                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1126                    postalias_props_sql = self.properties(
1127                        exp.Properties(
1128                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1129                        ),
1130                        wrapped=False,
1131                    )
1132                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1133                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1134
1135        postindex_props_sql = ""
1136        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1137            postindex_props_sql = self.properties(
1138                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1139                wrapped=False,
1140                prefix=" ",
1141            )
1142
1143        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1144        indexes = f" {indexes}" if indexes else ""
1145        index_sql = indexes + postindex_props_sql
1146
1147        replace = " OR REPLACE" if expression.args.get("replace") else ""
1148        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1149        unique = " UNIQUE" if expression.args.get("unique") else ""
1150
1151        clustered = expression.args.get("clustered")
1152        if clustered is None:
1153            clustered_sql = ""
1154        elif clustered:
1155            clustered_sql = " CLUSTERED COLUMNSTORE"
1156        else:
1157            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1158
1159        postcreate_props_sql = ""
1160        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1161            postcreate_props_sql = self.properties(
1162                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1163                sep=" ",
1164                prefix=" ",
1165                wrapped=False,
1166            )
1167
1168        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1169
1170        postexpression_props_sql = ""
1171        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1172            postexpression_props_sql = self.properties(
1173                exp.Properties(
1174                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1175                ),
1176                sep=" ",
1177                prefix=" ",
1178                wrapped=False,
1179            )
1180
1181        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1182        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1183        no_schema_binding = (
1184            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1185        )
1186
1187        clone = self.sql(expression, "clone")
1188        clone = f" {clone}" if clone else ""
1189
1190        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1191            properties_expression = f"{expression_sql}{properties_sql}"
1192        else:
1193            properties_expression = f"{properties_sql}{expression_sql}"
1194
1195        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1196        return self.prepend_ctes(expression, expression_sql)
1197
1198    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1199        start = self.sql(expression, "start")
1200        start = f"START WITH {start}" if start else ""
1201        increment = self.sql(expression, "increment")
1202        increment = f" INCREMENT BY {increment}" if increment else ""
1203        minvalue = self.sql(expression, "minvalue")
1204        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1205        maxvalue = self.sql(expression, "maxvalue")
1206        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1207        owned = self.sql(expression, "owned")
1208        owned = f" OWNED BY {owned}" if owned else ""
1209
1210        cache = expression.args.get("cache")
1211        if cache is None:
1212            cache_str = ""
1213        elif cache is True:
1214            cache_str = " CACHE"
1215        else:
1216            cache_str = f" CACHE {cache}"
1217
1218        options = self.expressions(expression, key="options", flat=True, sep=" ")
1219        options = f" {options}" if options else ""
1220
1221        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1222
1223    def clone_sql(self, expression: exp.Clone) -> str:
1224        this = self.sql(expression, "this")
1225        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1226        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1227        return f"{shallow}{keyword} {this}"
1228
1229    def describe_sql(self, expression: exp.Describe) -> str:
1230        style = expression.args.get("style")
1231        style = f" {style}" if style else ""
1232        partition = self.sql(expression, "partition")
1233        partition = f" {partition}" if partition else ""
1234        format = self.sql(expression, "format")
1235        format = f" {format}" if format else ""
1236
1237        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1238
1239    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1240        tag = self.sql(expression, "tag")
1241        return f"${tag}${self.sql(expression, 'this')}${tag}$"
1242
1243    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1244        with_ = self.sql(expression, "with")
1245        if with_:
1246            sql = f"{with_}{self.sep()}{sql}"
1247        return sql
1248
1249    def with_sql(self, expression: exp.With) -> str:
1250        sql = self.expressions(expression, flat=True)
1251        recursive = (
1252            "RECURSIVE "
1253            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1254            else ""
1255        )
1256        search = self.sql(expression, "search")
1257        search = f" {search}" if search else ""
1258
1259        return f"WITH {recursive}{sql}{search}"
1260
1261    def cte_sql(self, expression: exp.CTE) -> str:
1262        alias = expression.args.get("alias")
1263        if alias:
1264            alias.add_comments(expression.pop_comments())
1265
1266        alias_sql = self.sql(expression, "alias")
1267
1268        materialized = expression.args.get("materialized")
1269        if materialized is False:
1270            materialized = "NOT MATERIALIZED "
1271        elif materialized:
1272            materialized = "MATERIALIZED "
1273
1274        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1275
1276    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1277        alias = self.sql(expression, "this")
1278        columns = self.expressions(expression, key="columns", flat=True)
1279        columns = f"({columns})" if columns else ""
1280
1281        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1282            columns = ""
1283            self.unsupported("Named columns are not supported in table alias.")
1284
1285        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1286            alias = self._next_name()
1287
1288        return f"{alias}{columns}"
1289
1290    def bitstring_sql(self, expression: exp.BitString) -> str:
1291        this = self.sql(expression, "this")
1292        if self.dialect.BIT_START:
1293            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1294        return f"{int(this, 2)}"
1295
1296    def hexstring_sql(
1297        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1298    ) -> str:
1299        this = self.sql(expression, "this")
1300        is_integer_type = expression.args.get("is_integer")
1301
1302        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1303            not self.dialect.HEX_START and not binary_function_repr
1304        ):
1305            # Integer representation will be returned if:
1306            # - The read dialect treats the hex value as integer literal but not the write
1307            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1308            return f"{int(this, 16)}"
1309
1310        if not is_integer_type:
1311            # Read dialect treats the hex value as BINARY/BLOB
1312            if binary_function_repr:
1313                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1314                return self.func(binary_function_repr, exp.Literal.string(this))
1315            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1316                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1317                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1318
1319        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1320
1321    def bytestring_sql(self, expression: exp.ByteString) -> str:
1322        this = self.sql(expression, "this")
1323        if self.dialect.BYTE_START:
1324            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1325        return this
1326
1327    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1328        this = self.sql(expression, "this")
1329        escape = expression.args.get("escape")
1330
1331        if self.dialect.UNICODE_START:
1332            escape_substitute = r"\\\1"
1333            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1334        else:
1335            escape_substitute = r"\\u\1"
1336            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1337
1338        if escape:
1339            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1340            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1341        else:
1342            escape_pattern = ESCAPED_UNICODE_RE
1343            escape_sql = ""
1344
1345        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1346            this = escape_pattern.sub(escape_substitute, this)
1347
1348        return f"{left_quote}{this}{right_quote}{escape_sql}"
1349
1350    def rawstring_sql(self, expression: exp.RawString) -> str:
1351        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
1352        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
1353
1354    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1355        this = self.sql(expression, "this")
1356        specifier = self.sql(expression, "expression")
1357        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1358        return f"{this}{specifier}"
1359
1360    def datatype_sql(self, expression: exp.DataType) -> str:
1361        nested = ""
1362        values = ""
1363        interior = self.expressions(expression, flat=True)
1364
1365        type_value = expression.this
1366        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1367            type_sql = self.sql(expression, "kind")
1368        else:
1369            type_sql = (
1370                self.TYPE_MAPPING.get(type_value, type_value.value)
1371                if isinstance(type_value, exp.DataType.Type)
1372                else type_value
1373            )
1374
1375        if interior:
1376            if expression.args.get("nested"):
1377                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1378                if expression.args.get("values") is not None:
1379                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1380                    values = self.expressions(expression, key="values", flat=True)
1381                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1382            elif type_value == exp.DataType.Type.INTERVAL:
1383                nested = f" {interior}"
1384            else:
1385                nested = f"({interior})"
1386
1387        type_sql = f"{type_sql}{nested}{values}"
1388        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1389            exp.DataType.Type.TIMETZ,
1390            exp.DataType.Type.TIMESTAMPTZ,
1391        ):
1392            type_sql = f"{type_sql} WITH TIME ZONE"
1393
1394        return type_sql
1395
1396    def directory_sql(self, expression: exp.Directory) -> str:
1397        local = "LOCAL " if expression.args.get("local") else ""
1398        row_format = self.sql(expression, "row_format")
1399        row_format = f" {row_format}" if row_format else ""
1400        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1401
1402    def delete_sql(self, expression: exp.Delete) -> str:
1403        this = self.sql(expression, "this")
1404        this = f" FROM {this}" if this else ""
1405        using = self.sql(expression, "using")
1406        using = f" USING {using}" if using else ""
1407        cluster = self.sql(expression, "cluster")
1408        cluster = f" {cluster}" if cluster else ""
1409        where = self.sql(expression, "where")
1410        returning = self.sql(expression, "returning")
1411        limit = self.sql(expression, "limit")
1412        tables = self.expressions(expression, key="tables")
1413        tables = f" {tables}" if tables else ""
1414        if self.RETURNING_END:
1415            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1416        else:
1417            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1418        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1419
1420    def drop_sql(self, expression: exp.Drop) -> str:
1421        this = self.sql(expression, "this")
1422        expressions = self.expressions(expression, flat=True)
1423        expressions = f" ({expressions})" if expressions else ""
1424        kind = expression.args["kind"]
1425        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1426        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1427        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1428        on_cluster = self.sql(expression, "cluster")
1429        on_cluster = f" {on_cluster}" if on_cluster else ""
1430        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1431        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1432        cascade = " CASCADE" if expression.args.get("cascade") else ""
1433        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1434        purge = " PURGE" if expression.args.get("purge") else ""
1435        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1436
1437    def set_operation(self, expression: exp.SetOperation) -> str:
1438        op_type = type(expression)
1439        op_name = op_type.key.upper()
1440
1441        distinct = expression.args.get("distinct")
1442        if (
1443            distinct is False
1444            and op_type in (exp.Except, exp.Intersect)
1445            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1446        ):
1447            self.unsupported(f"{op_name} ALL is not supported")
1448
1449        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1450
1451        if distinct is None:
1452            distinct = default_distinct
1453            if distinct is None:
1454                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1455
1456        if distinct is default_distinct:
1457            distinct_or_all = ""
1458        else:
1459            distinct_or_all = " DISTINCT" if distinct else " ALL"
1460
1461        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1462        side_kind = f"{side_kind} " if side_kind else ""
1463
1464        by_name = " BY NAME" if expression.args.get("by_name") else ""
1465        on = self.expressions(expression, key="on", flat=True)
1466        on = f" ON ({on})" if on else ""
1467
1468        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
1469
1470    def set_operations(self, expression: exp.SetOperation) -> str:
1471        if not self.SET_OP_MODIFIERS:
1472            limit = expression.args.get("limit")
1473            order = expression.args.get("order")
1474
1475            if limit or order:
1476                select = self._move_ctes_to_top_level(
1477                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1478                )
1479
1480                if limit:
1481                    select = select.limit(limit.pop(), copy=False)
1482                if order:
1483                    select = select.order_by(order.pop(), copy=False)
1484                return self.sql(select)
1485
1486        sqls: t.List[str] = []
1487        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1488
1489        while stack:
1490            node = stack.pop()
1491
1492            if isinstance(node, exp.SetOperation):
1493                stack.append(node.expression)
1494                stack.append(
1495                    self.maybe_comment(
1496                        self.set_operation(node), comments=node.comments, separated=True
1497                    )
1498                )
1499                stack.append(node.this)
1500            else:
1501                sqls.append(self.sql(node))
1502
1503        this = self.sep().join(sqls)
1504        this = self.query_modifiers(expression, this)
1505        return self.prepend_ctes(expression, this)
1506
1507    def fetch_sql(self, expression: exp.Fetch) -> str:
1508        direction = expression.args.get("direction")
1509        direction = f" {direction}" if direction else ""
1510        count = self.sql(expression, "count")
1511        count = f" {count}" if count else ""
1512        limit_options = self.sql(expression, "limit_options")
1513        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1514        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1515
1516    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1517        percent = " PERCENT" if expression.args.get("percent") else ""
1518        rows = " ROWS" if expression.args.get("rows") else ""
1519        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1520        if not with_ties and rows:
1521            with_ties = " ONLY"
1522        return f"{percent}{rows}{with_ties}"
1523
1524    def filter_sql(self, expression: exp.Filter) -> str:
1525        if self.AGGREGATE_FILTER_SUPPORTED:
1526            this = self.sql(expression, "this")
1527            where = self.sql(expression, "expression").strip()
1528            return f"{this} FILTER({where})"
1529
1530        agg = expression.this
1531        agg_arg = agg.this
1532        cond = expression.expression.this
1533        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1534        return self.sql(agg)
1535
1536    def hint_sql(self, expression: exp.Hint) -> str:
1537        if not self.QUERY_HINTS:
1538            self.unsupported("Hints are not supported")
1539            return ""
1540
1541        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
1542
1543    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1544        using = self.sql(expression, "using")
1545        using = f" USING {using}" if using else ""
1546        columns = self.expressions(expression, key="columns", flat=True)
1547        columns = f"({columns})" if columns else ""
1548        partition_by = self.expressions(expression, key="partition_by", flat=True)
1549        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1550        where = self.sql(expression, "where")
1551        include = self.expressions(expression, key="include", flat=True)
1552        if include:
1553            include = f" INCLUDE ({include})"
1554        with_storage = self.expressions(expression, key="with_storage", flat=True)
1555        with_storage = f" WITH ({with_storage})" if with_storage else ""
1556        tablespace = self.sql(expression, "tablespace")
1557        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1558        on = self.sql(expression, "on")
1559        on = f" ON {on}" if on else ""
1560
1561        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1562
1563    def index_sql(self, expression: exp.Index) -> str:
1564        unique = "UNIQUE " if expression.args.get("unique") else ""
1565        primary = "PRIMARY " if expression.args.get("primary") else ""
1566        amp = "AMP " if expression.args.get("amp") else ""
1567        name = self.sql(expression, "this")
1568        name = f"{name} " if name else ""
1569        table = self.sql(expression, "table")
1570        table = f"{self.INDEX_ON} {table}" if table else ""
1571
1572        index = "INDEX " if not table else ""
1573
1574        params = self.sql(expression, "params")
1575        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1576
1577    def identifier_sql(self, expression: exp.Identifier) -> str:
1578        text = expression.name
1579        lower = text.lower()
1580        text = lower if self.normalize and not expression.quoted else text
1581        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1582        if (
1583            expression.quoted
1584            or self.dialect.can_identify(text, self.identify)
1585            or lower in self.RESERVED_KEYWORDS
1586            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1587        ):
1588            text = f"{self._identifier_start}{text}{self._identifier_end}"
1589        return text
1590
1591    def hex_sql(self, expression: exp.Hex) -> str:
1592        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1593        if self.dialect.HEX_LOWERCASE:
1594            text = self.func("LOWER", text)
1595
1596        return text
1597
1598    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1599        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1600        if not self.dialect.HEX_LOWERCASE:
1601            text = self.func("LOWER", text)
1602        return text
1603
1604    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1605        input_format = self.sql(expression, "input_format")
1606        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1607        output_format = self.sql(expression, "output_format")
1608        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1609        return self.sep().join((input_format, output_format))
1610
1611    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1612        string = self.sql(exp.Literal.string(expression.name))
1613        return f"{prefix}{string}"
1614
1615    def partition_sql(self, expression: exp.Partition) -> str:
1616        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1617        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
1618
1619    def properties_sql(self, expression: exp.Properties) -> str:
1620        root_properties = []
1621        with_properties = []
1622
1623        for p in expression.expressions:
1624            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1625            if p_loc == exp.Properties.Location.POST_WITH:
1626                with_properties.append(p)
1627            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1628                root_properties.append(p)
1629
1630        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1631        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1632
1633        if root_props and with_props and not self.pretty:
1634            with_props = " " + with_props
1635
1636        return root_props + with_props
1637
1638    def root_properties(self, properties: exp.Properties) -> str:
1639        if properties.expressions:
1640            return self.expressions(properties, indent=False, sep=" ")
1641        return ""
1642
1643    def properties(
1644        self,
1645        properties: exp.Properties,
1646        prefix: str = "",
1647        sep: str = ", ",
1648        suffix: str = "",
1649        wrapped: bool = True,
1650    ) -> str:
1651        if properties.expressions:
1652            expressions = self.expressions(properties, sep=sep, indent=False)
1653            if expressions:
1654                expressions = self.wrap(expressions) if wrapped else expressions
1655                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1656        return ""
1657
1658    def with_properties(self, properties: exp.Properties) -> str:
1659        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
1660
1661    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1662        properties_locs = defaultdict(list)
1663        for p in properties.expressions:
1664            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1665            if p_loc != exp.Properties.Location.UNSUPPORTED:
1666                properties_locs[p_loc].append(p)
1667            else:
1668                self.unsupported(f"Unsupported property {p.key}")
1669
1670        return properties_locs
1671
1672    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1673        if isinstance(expression.this, exp.Dot):
1674            return self.sql(expression, "this")
1675        return f"'{expression.name}'" if string_key else expression.name
1676
1677    def property_sql(self, expression: exp.Property) -> str:
1678        property_cls = expression.__class__
1679        if property_cls == exp.Property:
1680            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1681
1682        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1683        if not property_name:
1684            self.unsupported(f"Unsupported property {expression.key}")
1685
1686        return f"{property_name}={self.sql(expression, 'this')}"
1687
1688    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1689        if self.SUPPORTS_CREATE_TABLE_LIKE:
1690            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1691            options = f" {options}" if options else ""
1692
1693            like = f"LIKE {self.sql(expression, 'this')}{options}"
1694            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1695                like = f"({like})"
1696
1697            return like
1698
1699        if expression.expressions:
1700            self.unsupported("Transpilation of LIKE property options is unsupported")
1701
1702        select = exp.select("*").from_(expression.this).limit(0)
1703        return f"AS {self.sql(select)}"
1704
1705    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1706        no = "NO " if expression.args.get("no") else ""
1707        protection = " PROTECTION" if expression.args.get("protection") else ""
1708        return f"{no}FALLBACK{protection}"
1709
1710    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1711        no = "NO " if expression.args.get("no") else ""
1712        local = expression.args.get("local")
1713        local = f"{local} " if local else ""
1714        dual = "DUAL " if expression.args.get("dual") else ""
1715        before = "BEFORE " if expression.args.get("before") else ""
1716        after = "AFTER " if expression.args.get("after") else ""
1717        return f"{no}{local}{dual}{before}{after}JOURNAL"
1718
1719    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1720        freespace = self.sql(expression, "this")
1721        percent = " PERCENT" if expression.args.get("percent") else ""
1722        return f"FREESPACE={freespace}{percent}"
1723
1724    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1725        if expression.args.get("default"):
1726            property = "DEFAULT"
1727        elif expression.args.get("on"):
1728            property = "ON"
1729        else:
1730            property = "OFF"
1731        return f"CHECKSUM={property}"
1732
1733    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1734        if expression.args.get("no"):
1735            return "NO MERGEBLOCKRATIO"
1736        if expression.args.get("default"):
1737            return "DEFAULT MERGEBLOCKRATIO"
1738
1739        percent = " PERCENT" if expression.args.get("percent") else ""
1740        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1741
1742    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1743        default = expression.args.get("default")
1744        minimum = expression.args.get("minimum")
1745        maximum = expression.args.get("maximum")
1746        if default or minimum or maximum:
1747            if default:
1748                prop = "DEFAULT"
1749            elif minimum:
1750                prop = "MINIMUM"
1751            else:
1752                prop = "MAXIMUM"
1753            return f"{prop} DATABLOCKSIZE"
1754        units = expression.args.get("units")
1755        units = f" {units}" if units else ""
1756        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
1757
1758    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1759        autotemp = expression.args.get("autotemp")
1760        always = expression.args.get("always")
1761        default = expression.args.get("default")
1762        manual = expression.args.get("manual")
1763        never = expression.args.get("never")
1764
1765        if autotemp is not None:
1766            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1767        elif always:
1768            prop = "ALWAYS"
1769        elif default:
1770            prop = "DEFAULT"
1771        elif manual:
1772            prop = "MANUAL"
1773        elif never:
1774            prop = "NEVER"
1775        return f"BLOCKCOMPRESSION={prop}"
1776
1777    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1778        no = expression.args.get("no")
1779        no = " NO" if no else ""
1780        concurrent = expression.args.get("concurrent")
1781        concurrent = " CONCURRENT" if concurrent else ""
1782        target = self.sql(expression, "target")
1783        target = f" {target}" if target else ""
1784        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1785
1786    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1787        if isinstance(expression.this, list):
1788            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1789        if expression.this:
1790            modulus = self.sql(expression, "this")
1791            remainder = self.sql(expression, "expression")
1792            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1793
1794        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1795        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1796        return f"FROM ({from_expressions}) TO ({to_expressions})"
1797
1798    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1799        this = self.sql(expression, "this")
1800
1801        for_values_or_default = expression.expression
1802        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1803            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1804        else:
1805            for_values_or_default = " DEFAULT"
1806
1807        return f"PARTITION OF {this}{for_values_or_default}"
1808
1809    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1810        kind = expression.args.get("kind")
1811        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1812        for_or_in = expression.args.get("for_or_in")
1813        for_or_in = f" {for_or_in}" if for_or_in else ""
1814        lock_type = expression.args.get("lock_type")
1815        override = " OVERRIDE" if expression.args.get("override") else ""
1816        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1817
1818    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1819        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1820        statistics = expression.args.get("statistics")
1821        statistics_sql = ""
1822        if statistics is not None:
1823            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1824        return f"{data_sql}{statistics_sql}"
1825
1826    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1827        this = self.sql(expression, "this")
1828        this = f"HISTORY_TABLE={this}" if this else ""
1829        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1830        data_consistency = (
1831            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1832        )
1833        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1834        retention_period = (
1835            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1836        )
1837
1838        if this:
1839            on_sql = self.func("ON", this, data_consistency, retention_period)
1840        else:
1841            on_sql = "ON" if expression.args.get("on") else "OFF"
1842
1843        sql = f"SYSTEM_VERSIONING={on_sql}"
1844
1845        return f"WITH({sql})" if expression.args.get("with") else sql
1846
1847    def insert_sql(self, expression: exp.Insert) -> str:
1848        hint = self.sql(expression, "hint")
1849        overwrite = expression.args.get("overwrite")
1850
1851        if isinstance(expression.this, exp.Directory):
1852            this = " OVERWRITE" if overwrite else " INTO"
1853        else:
1854            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1855
1856        stored = self.sql(expression, "stored")
1857        stored = f" {stored}" if stored else ""
1858        alternative = expression.args.get("alternative")
1859        alternative = f" OR {alternative}" if alternative else ""
1860        ignore = " IGNORE" if expression.args.get("ignore") else ""
1861        is_function = expression.args.get("is_function")
1862        if is_function:
1863            this = f"{this} FUNCTION"
1864        this = f"{this} {self.sql(expression, 'this')}"
1865
1866        exists = " IF EXISTS" if expression.args.get("exists") else ""
1867        where = self.sql(expression, "where")
1868        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1869        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1870        on_conflict = self.sql(expression, "conflict")
1871        on_conflict = f" {on_conflict}" if on_conflict else ""
1872        by_name = " BY NAME" if expression.args.get("by_name") else ""
1873        returning = self.sql(expression, "returning")
1874
1875        if self.RETURNING_END:
1876            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1877        else:
1878            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1879
1880        partition_by = self.sql(expression, "partition")
1881        partition_by = f" {partition_by}" if partition_by else ""
1882        settings = self.sql(expression, "settings")
1883        settings = f" {settings}" if settings else ""
1884
1885        source = self.sql(expression, "source")
1886        source = f"TABLE {source}" if source else ""
1887
1888        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1889        return self.prepend_ctes(expression, sql)
1890
1891    def introducer_sql(self, expression: exp.Introducer) -> str:
1892        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
1893
1894    def kill_sql(self, expression: exp.Kill) -> str:
1895        kind = self.sql(expression, "kind")
1896        kind = f" {kind}" if kind else ""
1897        this = self.sql(expression, "this")
1898        this = f" {this}" if this else ""
1899        return f"KILL{kind}{this}"
1900
1901    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1902        return expression.name
1903
1904    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1905        return expression.name
1906
1907    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1908        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1909
1910        constraint = self.sql(expression, "constraint")
1911        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1912
1913        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1914        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1915        action = self.sql(expression, "action")
1916
1917        expressions = self.expressions(expression, flat=True)
1918        if expressions:
1919            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1920            expressions = f" {set_keyword}{expressions}"
1921
1922        where = self.sql(expression, "where")
1923        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
1924
1925    def returning_sql(self, expression: exp.Returning) -> str:
1926        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
1927
1928    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1929        fields = self.sql(expression, "fields")
1930        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1931        escaped = self.sql(expression, "escaped")
1932        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1933        items = self.sql(expression, "collection_items")
1934        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1935        keys = self.sql(expression, "map_keys")
1936        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1937        lines = self.sql(expression, "lines")
1938        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1939        null = self.sql(expression, "null")
1940        null = f" NULL DEFINED AS {null}" if null else ""
1941        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1942
1943    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1944        return f"WITH ({self.expressions(expression, flat=True)})"
1945
1946    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1947        this = f"{self.sql(expression, 'this')} INDEX"
1948        target = self.sql(expression, "target")
1949        target = f" FOR {target}" if target else ""
1950        return f"{this}{target} ({self.expressions(expression, flat=True)})"
1951
1952    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1953        this = self.sql(expression, "this")
1954        kind = self.sql(expression, "kind")
1955        expr = self.sql(expression, "expression")
1956        return f"{this} ({kind} => {expr})"
1957
1958    def table_parts(self, expression: exp.Table) -> str:
1959        return ".".join(
1960            self.sql(part)
1961            for part in (
1962                expression.args.get("catalog"),
1963                expression.args.get("db"),
1964                expression.args.get("this"),
1965            )
1966            if part is not None
1967        )
1968
1969    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1970        table = self.table_parts(expression)
1971        only = "ONLY " if expression.args.get("only") else ""
1972        partition = self.sql(expression, "partition")
1973        partition = f" {partition}" if partition else ""
1974        version = self.sql(expression, "version")
1975        version = f" {version}" if version else ""
1976        alias = self.sql(expression, "alias")
1977        alias = f"{sep}{alias}" if alias else ""
1978
1979        sample = self.sql(expression, "sample")
1980        if self.dialect.ALIAS_POST_TABLESAMPLE:
1981            sample_pre_alias = sample
1982            sample_post_alias = ""
1983        else:
1984            sample_pre_alias = ""
1985            sample_post_alias = sample
1986
1987        hints = self.expressions(expression, key="hints", sep=" ")
1988        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
1989        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
1990        joins = self.indent(
1991            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
1992        )
1993        laterals = self.expressions(expression, key="laterals", sep="")
1994
1995        file_format = self.sql(expression, "format")
1996        if file_format:
1997            pattern = self.sql(expression, "pattern")
1998            pattern = f", PATTERN => {pattern}" if pattern else ""
1999            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
2000
2001        ordinality = expression.args.get("ordinality") or ""
2002        if ordinality:
2003            ordinality = f" WITH ORDINALITY{alias}"
2004            alias = ""
2005
2006        when = self.sql(expression, "when")
2007        if when:
2008            table = f"{table} {when}"
2009
2010        changes = self.sql(expression, "changes")
2011        changes = f" {changes}" if changes else ""
2012
2013        rows_from = self.expressions(expression, key="rows_from")
2014        if rows_from:
2015            table = f"ROWS FROM {self.wrap(rows_from)}"
2016
2017        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2018
2019    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2020        table = self.func("TABLE", expression.this)
2021        alias = self.sql(expression, "alias")
2022        alias = f" AS {alias}" if alias else ""
2023        sample = self.sql(expression, "sample")
2024        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2025        joins = self.indent(
2026            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2027        )
2028        return f"{table}{alias}{pivots}{sample}{joins}"
2029
2030    def tablesample_sql(
2031        self,
2032        expression: exp.TableSample,
2033        tablesample_keyword: t.Optional[str] = None,
2034    ) -> str:
2035        method = self.sql(expression, "method")
2036        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2037        numerator = self.sql(expression, "bucket_numerator")
2038        denominator = self.sql(expression, "bucket_denominator")
2039        field = self.sql(expression, "bucket_field")
2040        field = f" ON {field}" if field else ""
2041        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2042        seed = self.sql(expression, "seed")
2043        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2044
2045        size = self.sql(expression, "size")
2046        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2047            size = f"{size} ROWS"
2048
2049        percent = self.sql(expression, "percent")
2050        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2051            percent = f"{percent} PERCENT"
2052
2053        expr = f"{bucket}{percent}{size}"
2054        if self.TABLESAMPLE_REQUIRES_PARENS:
2055            expr = f"({expr})"
2056
2057        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2058
2059    def pivot_sql(self, expression: exp.Pivot) -> str:
2060        expressions = self.expressions(expression, flat=True)
2061        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2062
2063        group = self.sql(expression, "group")
2064
2065        if expression.this:
2066            this = self.sql(expression, "this")
2067            if not expressions:
2068                return f"UNPIVOT {this}"
2069
2070            on = f"{self.seg('ON')} {expressions}"
2071            into = self.sql(expression, "into")
2072            into = f"{self.seg('INTO')} {into}" if into else ""
2073            using = self.expressions(expression, key="using", flat=True)
2074            using = f"{self.seg('USING')} {using}" if using else ""
2075            return f"{direction} {this}{on}{into}{using}{group}"
2076
2077        alias = self.sql(expression, "alias")
2078        alias = f" AS {alias}" if alias else ""
2079
2080        fields = self.expressions(
2081            expression,
2082            "fields",
2083            sep=" ",
2084            dynamic=True,
2085            new_line=True,
2086            skip_first=True,
2087            skip_last=True,
2088        )
2089
2090        include_nulls = expression.args.get("include_nulls")
2091        if include_nulls is not None:
2092            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2093        else:
2094            nulls = ""
2095
2096        default_on_null = self.sql(expression, "default_on_null")
2097        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2098        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
2099
2100    def version_sql(self, expression: exp.Version) -> str:
2101        this = f"FOR {expression.name}"
2102        kind = expression.text("kind")
2103        expr = self.sql(expression, "expression")
2104        return f"{this} {kind} {expr}"
2105
2106    def tuple_sql(self, expression: exp.Tuple) -> str:
2107        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
2108
2109    def update_sql(self, expression: exp.Update) -> str:
2110        this = self.sql(expression, "this")
2111        set_sql = self.expressions(expression, flat=True)
2112        from_sql = self.sql(expression, "from")
2113        where_sql = self.sql(expression, "where")
2114        returning = self.sql(expression, "returning")
2115        order = self.sql(expression, "order")
2116        limit = self.sql(expression, "limit")
2117        if self.RETURNING_END:
2118            expression_sql = f"{from_sql}{where_sql}{returning}"
2119        else:
2120            expression_sql = f"{returning}{from_sql}{where_sql}"
2121        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2122        return self.prepend_ctes(expression, sql)
2123
2124    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2125        values_as_table = values_as_table and self.VALUES_AS_TABLE
2126
2127        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2128        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2129            args = self.expressions(expression)
2130            alias = self.sql(expression, "alias")
2131            values = f"VALUES{self.seg('')}{args}"
2132            values = (
2133                f"({values})"
2134                if self.WRAP_DERIVED_VALUES
2135                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2136                else values
2137            )
2138            return f"{values} AS {alias}" if alias else values
2139
2140        # Converts `VALUES...` expression into a series of select unions.
2141        alias_node = expression.args.get("alias")
2142        column_names = alias_node and alias_node.columns
2143
2144        selects: t.List[exp.Query] = []
2145
2146        for i, tup in enumerate(expression.expressions):
2147            row = tup.expressions
2148
2149            if i == 0 and column_names:
2150                row = [
2151                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2152                ]
2153
2154            selects.append(exp.Select(expressions=row))
2155
2156        if self.pretty:
2157            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2158            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2159            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2160            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2161            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2162
2163        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2164        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2165        return f"({unions}){alias}"
2166
2167    def var_sql(self, expression: exp.Var) -> str:
2168        return self.sql(expression, "this")
2169
2170    @unsupported_args("expressions")
2171    def into_sql(self, expression: exp.Into) -> str:
2172        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2173        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2174        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2175
2176    def from_sql(self, expression: exp.From) -> str:
2177        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
2178
2179    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2180        grouping_sets = self.expressions(expression, indent=False)
2181        return f"GROUPING SETS {self.wrap(grouping_sets)}"
2182
2183    def rollup_sql(self, expression: exp.Rollup) -> str:
2184        expressions = self.expressions(expression, indent=False)
2185        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
2186
2187    def cube_sql(self, expression: exp.Cube) -> str:
2188        expressions = self.expressions(expression, indent=False)
2189        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
2190
2191    def group_sql(self, expression: exp.Group) -> str:
2192        group_by_all = expression.args.get("all")
2193        if group_by_all is True:
2194            modifier = " ALL"
2195        elif group_by_all is False:
2196            modifier = " DISTINCT"
2197        else:
2198            modifier = ""
2199
2200        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2201
2202        grouping_sets = self.expressions(expression, key="grouping_sets")
2203        cube = self.expressions(expression, key="cube")
2204        rollup = self.expressions(expression, key="rollup")
2205
2206        groupings = csv(
2207            self.seg(grouping_sets) if grouping_sets else "",
2208            self.seg(cube) if cube else "",
2209            self.seg(rollup) if rollup else "",
2210            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2211            sep=self.GROUPINGS_SEP,
2212        )
2213
2214        if (
2215            expression.expressions
2216            and groupings
2217            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2218        ):
2219            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2220
2221        return f"{group_by}{groupings}"
2222
2223    def having_sql(self, expression: exp.Having) -> str:
2224        this = self.indent(self.sql(expression, "this"))
2225        return f"{self.seg('HAVING')}{self.sep()}{this}"
2226
2227    def connect_sql(self, expression: exp.Connect) -> str:
2228        start = self.sql(expression, "start")
2229        start = self.seg(f"START WITH {start}") if start else ""
2230        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2231        connect = self.sql(expression, "connect")
2232        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2233        return start + connect
2234
2235    def prior_sql(self, expression: exp.Prior) -> str:
2236        return f"PRIOR {self.sql(expression, 'this')}"
2237
2238    def join_sql(self, expression: exp.Join) -> str:
2239        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2240            side = None
2241        else:
2242            side = expression.side
2243
2244        op_sql = " ".join(
2245            op
2246            for op in (
2247                expression.method,
2248                "GLOBAL" if expression.args.get("global") else None,
2249                side,
2250                expression.kind,
2251                expression.hint if self.JOIN_HINTS else None,
2252            )
2253            if op
2254        )
2255        match_cond = self.sql(expression, "match_condition")
2256        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2257        on_sql = self.sql(expression, "on")
2258        using = expression.args.get("using")
2259
2260        if not on_sql and using:
2261            on_sql = csv(*(self.sql(column) for column in using))
2262
2263        this = expression.this
2264        this_sql = self.sql(this)
2265
2266        exprs = self.expressions(expression)
2267        if exprs:
2268            this_sql = f"{this_sql},{self.seg(exprs)}"
2269
2270        if on_sql:
2271            on_sql = self.indent(on_sql, skip_first=True)
2272            space = self.seg(" " * self.pad) if self.pretty else " "
2273            if using:
2274                on_sql = f"{space}USING ({on_sql})"
2275            else:
2276                on_sql = f"{space}ON {on_sql}"
2277        elif not op_sql:
2278            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2279                return f" {this_sql}"
2280
2281            return f", {this_sql}"
2282
2283        if op_sql != "STRAIGHT_JOIN":
2284            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2285
2286        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2287
2288    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2289        args = self.expressions(expression, flat=True)
2290        args = f"({args})" if len(args.split(",")) > 1 else args
2291        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
2292
2293    def lateral_op(self, expression: exp.Lateral) -> str:
2294        cross_apply = expression.args.get("cross_apply")
2295
2296        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2297        if cross_apply is True:
2298            op = "INNER JOIN "
2299        elif cross_apply is False:
2300            op = "LEFT JOIN "
2301        else:
2302            op = ""
2303
2304        return f"{op}LATERAL"
2305
2306    def lateral_sql(self, expression: exp.Lateral) -> str:
2307        this = self.sql(expression, "this")
2308
2309        if expression.args.get("view"):
2310            alias = expression.args["alias"]
2311            columns = self.expressions(alias, key="columns", flat=True)
2312            table = f" {alias.name}" if alias.name else ""
2313            columns = f" AS {columns}" if columns else ""
2314            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2315            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2316
2317        alias = self.sql(expression, "alias")
2318        alias = f" AS {alias}" if alias else ""
2319
2320        ordinality = expression.args.get("ordinality") or ""
2321        if ordinality:
2322            ordinality = f" WITH ORDINALITY{alias}"
2323            alias = ""
2324
2325        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
2326
2327    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2328        this = self.sql(expression, "this")
2329
2330        args = [
2331            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2332            for e in (expression.args.get(k) for k in ("offset", "expression"))
2333            if e
2334        ]
2335
2336        args_sql = ", ".join(self.sql(e) for e in args)
2337        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2338        expressions = self.expressions(expression, flat=True)
2339        limit_options = self.sql(expression, "limit_options")
2340        expressions = f" BY {expressions}" if expressions else ""
2341
2342        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2343
2344    def offset_sql(self, expression: exp.Offset) -> str:
2345        this = self.sql(expression, "this")
2346        value = expression.expression
2347        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2348        expressions = self.expressions(expression, flat=True)
2349        expressions = f" BY {expressions}" if expressions else ""
2350        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2351
2352    def setitem_sql(self, expression: exp.SetItem) -> str:
2353        kind = self.sql(expression, "kind")
2354        kind = f"{kind} " if kind else ""
2355        this = self.sql(expression, "this")
2356        expressions = self.expressions(expression)
2357        collate = self.sql(expression, "collate")
2358        collate = f" COLLATE {collate}" if collate else ""
2359        global_ = "GLOBAL " if expression.args.get("global") else ""
2360        return f"{global_}{kind}{this}{expressions}{collate}"
2361
2362    def set_sql(self, expression: exp.Set) -> str:
2363        expressions = f" {self.expressions(expression, flat=True)}"
2364        tag = " TAG" if expression.args.get("tag") else ""
2365        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2366
2367    def pragma_sql(self, expression: exp.Pragma) -> str:
2368        return f"PRAGMA {self.sql(expression, 'this')}"
2369
2370    def lock_sql(self, expression: exp.Lock) -> str:
2371        if not self.LOCKING_READS_SUPPORTED:
2372            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2373            return ""
2374
2375        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2376        expressions = self.expressions(expression, flat=True)
2377        expressions = f" OF {expressions}" if expressions else ""
2378        wait = expression.args.get("wait")
2379
2380        if wait is not None:
2381            if isinstance(wait, exp.Literal):
2382                wait = f" WAIT {self.sql(wait)}"
2383            else:
2384                wait = " NOWAIT" if wait else " SKIP LOCKED"
2385
2386        return f"{lock_type}{expressions}{wait or ''}"
2387
2388    def literal_sql(self, expression: exp.Literal) -> str:
2389        text = expression.this or ""
2390        if expression.is_string:
2391            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2392        return text
2393
2394    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2395        if self.dialect.ESCAPED_SEQUENCES:
2396            to_escaped = self.dialect.ESCAPED_SEQUENCES
2397            text = "".join(
2398                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2399            )
2400
2401        return self._replace_line_breaks(text).replace(
2402            self.dialect.QUOTE_END, self._escaped_quote_end
2403        )
2404
2405    def loaddata_sql(self, expression: exp.LoadData) -> str:
2406        local = " LOCAL" if expression.args.get("local") else ""
2407        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2408        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2409        this = f" INTO TABLE {self.sql(expression, 'this')}"
2410        partition = self.sql(expression, "partition")
2411        partition = f" {partition}" if partition else ""
2412        input_format = self.sql(expression, "input_format")
2413        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2414        serde = self.sql(expression, "serde")
2415        serde = f" SERDE {serde}" if serde else ""
2416        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2417
2418    def null_sql(self, *_) -> str:
2419        return "NULL"
2420
2421    def boolean_sql(self, expression: exp.Boolean) -> str:
2422        return "TRUE" if expression.this else "FALSE"
2423
2424    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2425        this = self.sql(expression, "this")
2426        this = f"{this} " if this else this
2427        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2428        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
2429
2430    def withfill_sql(self, expression: exp.WithFill) -> str:
2431        from_sql = self.sql(expression, "from")
2432        from_sql = f" FROM {from_sql}" if from_sql else ""
2433        to_sql = self.sql(expression, "to")
2434        to_sql = f" TO {to_sql}" if to_sql else ""
2435        step_sql = self.sql(expression, "step")
2436        step_sql = f" STEP {step_sql}" if step_sql else ""
2437        interpolated_values = [
2438            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2439            if isinstance(e, exp.Alias)
2440            else self.sql(e, "this")
2441            for e in expression.args.get("interpolate") or []
2442        ]
2443        interpolate = (
2444            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2445        )
2446        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2447
2448    def cluster_sql(self, expression: exp.Cluster) -> str:
2449        return self.op_expressions("CLUSTER BY", expression)
2450
2451    def distribute_sql(self, expression: exp.Distribute) -> str:
2452        return self.op_expressions("DISTRIBUTE BY", expression)
2453
2454    def sort_sql(self, expression: exp.Sort) -> str:
2455        return self.op_expressions("SORT BY", expression)
2456
2457    def ordered_sql(self, expression: exp.Ordered) -> str:
2458        desc = expression.args.get("desc")
2459        asc = not desc
2460
2461        nulls_first = expression.args.get("nulls_first")
2462        nulls_last = not nulls_first
2463        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2464        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2465        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2466
2467        this = self.sql(expression, "this")
2468
2469        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2470        nulls_sort_change = ""
2471        if nulls_first and (
2472            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2473        ):
2474            nulls_sort_change = " NULLS FIRST"
2475        elif (
2476            nulls_last
2477            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2478            and not nulls_are_last
2479        ):
2480            nulls_sort_change = " NULLS LAST"
2481
2482        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2483        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2484            window = expression.find_ancestor(exp.Window, exp.Select)
2485            if isinstance(window, exp.Window) and window.args.get("spec"):
2486                self.unsupported(
2487                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2488                )
2489                nulls_sort_change = ""
2490            elif self.NULL_ORDERING_SUPPORTED is False and (
2491                (asc and nulls_sort_change == " NULLS LAST")
2492                or (desc and nulls_sort_change == " NULLS FIRST")
2493            ):
2494                # BigQuery does not allow these ordering/nulls combinations when used under
2495                # an aggregation func or under a window containing one
2496                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2497
2498                if isinstance(ancestor, exp.Window):
2499                    ancestor = ancestor.this
2500                if isinstance(ancestor, exp.AggFunc):
2501                    self.unsupported(
2502                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2503                    )
2504                    nulls_sort_change = ""
2505            elif self.NULL_ORDERING_SUPPORTED is None:
2506                if expression.this.is_int:
2507                    self.unsupported(
2508                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2509                    )
2510                elif not isinstance(expression.this, exp.Rand):
2511                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2512                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2513                nulls_sort_change = ""
2514
2515        with_fill = self.sql(expression, "with_fill")
2516        with_fill = f" {with_fill}" if with_fill else ""
2517
2518        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2519
2520    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2521        window_frame = self.sql(expression, "window_frame")
2522        window_frame = f"{window_frame} " if window_frame else ""
2523
2524        this = self.sql(expression, "this")
2525
2526        return f"{window_frame}{this}"
2527
2528    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2529        partition = self.partition_by_sql(expression)
2530        order = self.sql(expression, "order")
2531        measures = self.expressions(expression, key="measures")
2532        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2533        rows = self.sql(expression, "rows")
2534        rows = self.seg(rows) if rows else ""
2535        after = self.sql(expression, "after")
2536        after = self.seg(after) if after else ""
2537        pattern = self.sql(expression, "pattern")
2538        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2539        definition_sqls = [
2540            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2541            for definition in expression.args.get("define", [])
2542        ]
2543        definitions = self.expressions(sqls=definition_sqls)
2544        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2545        body = "".join(
2546            (
2547                partition,
2548                order,
2549                measures,
2550                rows,
2551                after,
2552                pattern,
2553                define,
2554            )
2555        )
2556        alias = self.sql(expression, "alias")
2557        alias = f" {alias}" if alias else ""
2558        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2559
2560    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2561        limit = expression.args.get("limit")
2562
2563        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2564            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2565        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2566            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2567
2568        return csv(
2569            *sqls,
2570            *[self.sql(join) for join in expression.args.get("joins") or []],
2571            self.sql(expression, "match"),
2572            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2573            self.sql(expression, "prewhere"),
2574            self.sql(expression, "where"),
2575            self.sql(expression, "connect"),
2576            self.sql(expression, "group"),
2577            self.sql(expression, "having"),
2578            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2579            self.sql(expression, "order"),
2580            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2581            *self.after_limit_modifiers(expression),
2582            self.options_modifier(expression),
2583            sep="",
2584        )
2585
2586    def options_modifier(self, expression: exp.Expression) -> str:
2587        options = self.expressions(expression, key="options")
2588        return f" {options}" if options else ""
2589
2590    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2591        self.unsupported("Unsupported query option.")
2592        return ""
2593
2594    def offset_limit_modifiers(
2595        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2596    ) -> t.List[str]:
2597        return [
2598            self.sql(expression, "offset") if fetch else self.sql(limit),
2599            self.sql(limit) if fetch else self.sql(expression, "offset"),
2600        ]
2601
2602    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2603        locks = self.expressions(expression, key="locks", sep=" ")
2604        locks = f" {locks}" if locks else ""
2605        return [locks, self.sql(expression, "sample")]
2606
2607    def select_sql(self, expression: exp.Select) -> str:
2608        into = expression.args.get("into")
2609        if not self.SUPPORTS_SELECT_INTO and into:
2610            into.pop()
2611
2612        hint = self.sql(expression, "hint")
2613        distinct = self.sql(expression, "distinct")
2614        distinct = f" {distinct}" if distinct else ""
2615        kind = self.sql(expression, "kind")
2616
2617        limit = expression.args.get("limit")
2618        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2619            top = self.limit_sql(limit, top=True)
2620            limit.pop()
2621        else:
2622            top = ""
2623
2624        expressions = self.expressions(expression)
2625
2626        if kind:
2627            if kind in self.SELECT_KINDS:
2628                kind = f" AS {kind}"
2629            else:
2630                if kind == "STRUCT":
2631                    expressions = self.expressions(
2632                        sqls=[
2633                            self.sql(
2634                                exp.Struct(
2635                                    expressions=[
2636                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2637                                        if isinstance(e, exp.Alias)
2638                                        else e
2639                                        for e in expression.expressions
2640                                    ]
2641                                )
2642                            )
2643                        ]
2644                    )
2645                kind = ""
2646
2647        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2648        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2649
2650        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2651        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2652        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2653        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2654        sql = self.query_modifiers(
2655            expression,
2656            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2657            self.sql(expression, "into", comment=False),
2658            self.sql(expression, "from", comment=False),
2659        )
2660
2661        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2662        if expression.args.get("with"):
2663            sql = self.maybe_comment(sql, expression)
2664            expression.pop_comments()
2665
2666        sql = self.prepend_ctes(expression, sql)
2667
2668        if not self.SUPPORTS_SELECT_INTO and into:
2669            if into.args.get("temporary"):
2670                table_kind = " TEMPORARY"
2671            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2672                table_kind = " UNLOGGED"
2673            else:
2674                table_kind = ""
2675            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2676
2677        return sql
2678
2679    def schema_sql(self, expression: exp.Schema) -> str:
2680        this = self.sql(expression, "this")
2681        sql = self.schema_columns_sql(expression)
2682        return f"{this} {sql}" if this and sql else this or sql
2683
2684    def schema_columns_sql(self, expression: exp.Schema) -> str:
2685        if expression.expressions:
2686            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2687        return ""
2688
2689    def star_sql(self, expression: exp.Star) -> str:
2690        except_ = self.expressions(expression, key="except", flat=True)
2691        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2692        replace = self.expressions(expression, key="replace", flat=True)
2693        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2694        rename = self.expressions(expression, key="rename", flat=True)
2695        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2696        return f"*{except_}{replace}{rename}"
2697
2698    def parameter_sql(self, expression: exp.Parameter) -> str:
2699        this = self.sql(expression, "this")
2700        return f"{self.PARAMETER_TOKEN}{this}"
2701
2702    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2703        this = self.sql(expression, "this")
2704        kind = expression.text("kind")
2705        if kind:
2706            kind = f"{kind}."
2707        return f"@@{kind}{this}"
2708
2709    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2710        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
2711
2712    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2713        alias = self.sql(expression, "alias")
2714        alias = f"{sep}{alias}" if alias else ""
2715        sample = self.sql(expression, "sample")
2716        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2717            alias = f"{sample}{alias}"
2718
2719            # Set to None so it's not generated again by self.query_modifiers()
2720            expression.set("sample", None)
2721
2722        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2723        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2724        return self.prepend_ctes(expression, sql)
2725
2726    def qualify_sql(self, expression: exp.Qualify) -> str:
2727        this = self.indent(self.sql(expression, "this"))
2728        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
2729
2730    def unnest_sql(self, expression: exp.Unnest) -> str:
2731        args = self.expressions(expression, flat=True)
2732
2733        alias = expression.args.get("alias")
2734        offset = expression.args.get("offset")
2735
2736        if self.UNNEST_WITH_ORDINALITY:
2737            if alias and isinstance(offset, exp.Expression):
2738                alias.append("columns", offset)
2739
2740        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2741            columns = alias.columns
2742            alias = self.sql(columns[0]) if columns else ""
2743        else:
2744            alias = self.sql(alias)
2745
2746        alias = f" AS {alias}" if alias else alias
2747        if self.UNNEST_WITH_ORDINALITY:
2748            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2749        else:
2750            if isinstance(offset, exp.Expression):
2751                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2752            elif offset:
2753                suffix = f"{alias} WITH OFFSET"
2754            else:
2755                suffix = alias
2756
2757        return f"UNNEST({args}){suffix}"
2758
2759    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2760        return ""
2761
2762    def where_sql(self, expression: exp.Where) -> str:
2763        this = self.indent(self.sql(expression, "this"))
2764        return f"{self.seg('WHERE')}{self.sep()}{this}"
2765
2766    def window_sql(self, expression: exp.Window) -> str:
2767        this = self.sql(expression, "this")
2768        partition = self.partition_by_sql(expression)
2769        order = expression.args.get("order")
2770        order = self.order_sql(order, flat=True) if order else ""
2771        spec = self.sql(expression, "spec")
2772        alias = self.sql(expression, "alias")
2773        over = self.sql(expression, "over") or "OVER"
2774
2775        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2776
2777        first = expression.args.get("first")
2778        if first is None:
2779            first = ""
2780        else:
2781            first = "FIRST" if first else "LAST"
2782
2783        if not partition and not order and not spec and alias:
2784            return f"{this} {alias}"
2785
2786        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
2787        return f"{this} ({args})"
2788
2789    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2790        partition = self.expressions(expression, key="partition_by", flat=True)
2791        return f"PARTITION BY {partition}" if partition else ""
2792
2793    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2794        kind = self.sql(expression, "kind")
2795        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2796        end = (
2797            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2798            or "CURRENT ROW"
2799        )
2800        return f"{kind} BETWEEN {start} AND {end}"
2801
2802    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2803        this = self.sql(expression, "this")
2804        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2805        return f"{this} WITHIN GROUP ({expression_sql})"
2806
2807    def between_sql(self, expression: exp.Between) -> str:
2808        this = self.sql(expression, "this")
2809        low = self.sql(expression, "low")
2810        high = self.sql(expression, "high")
2811        return f"{this} BETWEEN {low} AND {high}"
2812
2813    def bracket_offset_expressions(
2814        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2815    ) -> t.List[exp.Expression]:
2816        return apply_index_offset(
2817            expression.this,
2818            expression.expressions,
2819            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2820            dialect=self.dialect,
2821        )
2822
2823    def bracket_sql(self, expression: exp.Bracket) -> str:
2824        expressions = self.bracket_offset_expressions(expression)
2825        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2826        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
2827
2828    def all_sql(self, expression: exp.All) -> str:
2829        return f"ALL {self.wrap(expression)}"
2830
2831    def any_sql(self, expression: exp.Any) -> str:
2832        this = self.sql(expression, "this")
2833        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2834            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2835                this = self.wrap(this)
2836            return f"ANY{this}"
2837        return f"ANY {this}"
2838
2839    def exists_sql(self, expression: exp.Exists) -> str:
2840        return f"EXISTS{self.wrap(expression)}"
2841
2842    def case_sql(self, expression: exp.Case) -> str:
2843        this = self.sql(expression, "this")
2844        statements = [f"CASE {this}" if this else "CASE"]
2845
2846        for e in expression.args["ifs"]:
2847            statements.append(f"WHEN {self.sql(e, 'this')}")
2848            statements.append(f"THEN {self.sql(e, 'true')}")
2849
2850        default = self.sql(expression, "default")
2851
2852        if default:
2853            statements.append(f"ELSE {default}")
2854
2855        statements.append("END")
2856
2857        if self.pretty and self.too_wide(statements):
2858            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2859
2860        return " ".join(statements)
2861
2862    def constraint_sql(self, expression: exp.Constraint) -> str:
2863        this = self.sql(expression, "this")
2864        expressions = self.expressions(expression, flat=True)
2865        return f"CONSTRAINT {this} {expressions}"
2866
2867    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2868        order = expression.args.get("order")
2869        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2870        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
2871
2872    def extract_sql(self, expression: exp.Extract) -> str:
2873        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2874        expression_sql = self.sql(expression, "expression")
2875        return f"EXTRACT({this} FROM {expression_sql})"
2876
2877    def trim_sql(self, expression: exp.Trim) -> str:
2878        trim_type = self.sql(expression, "position")
2879
2880        if trim_type == "LEADING":
2881            func_name = "LTRIM"
2882        elif trim_type == "TRAILING":
2883            func_name = "RTRIM"
2884        else:
2885            func_name = "TRIM"
2886
2887        return self.func(func_name, expression.this, expression.expression)
2888
2889    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2890        args = expression.expressions
2891        if isinstance(expression, exp.ConcatWs):
2892            args = args[1:]  # Skip the delimiter
2893
2894        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2895            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2896
2897        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2898            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2899
2900        return args
2901
2902    def concat_sql(self, expression: exp.Concat) -> str:
2903        expressions = self.convert_concat_args(expression)
2904
2905        # Some dialects don't allow a single-argument CONCAT call
2906        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2907            return self.sql(expressions[0])
2908
2909        return self.func("CONCAT", *expressions)
2910
2911    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2912        return self.func(
2913            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2914        )
2915
2916    def check_sql(self, expression: exp.Check) -> str:
2917        this = self.sql(expression, key="this")
2918        return f"CHECK ({this})"
2919
2920    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2921        expressions = self.expressions(expression, flat=True)
2922        expressions = f" ({expressions})" if expressions else ""
2923        reference = self.sql(expression, "reference")
2924        reference = f" {reference}" if reference else ""
2925        delete = self.sql(expression, "delete")
2926        delete = f" ON DELETE {delete}" if delete else ""
2927        update = self.sql(expression, "update")
2928        update = f" ON UPDATE {update}" if update else ""
2929        options = self.expressions(expression, key="options", flat=True, sep=" ")
2930        options = f" {options}" if options else ""
2931        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
2932
2933    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2934        expressions = self.expressions(expression, flat=True)
2935        options = self.expressions(expression, key="options", flat=True, sep=" ")
2936        options = f" {options}" if options else ""
2937        return f"PRIMARY KEY ({expressions}){options}"
2938
2939    def if_sql(self, expression: exp.If) -> str:
2940        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
2941
2942    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2943        modifier = expression.args.get("modifier")
2944        modifier = f" {modifier}" if modifier else ""
2945        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
2946
2947    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2948        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
2949
2950    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2951        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2952
2953        if expression.args.get("escape"):
2954            path = self.escape_str(path)
2955
2956        if self.QUOTE_JSON_PATH:
2957            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2958
2959        return path
2960
2961    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
2962        if isinstance(expression, exp.JSONPathPart):
2963            transform = self.TRANSFORMS.get(expression.__class__)
2964            if not callable(transform):
2965                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
2966                return ""
2967
2968            return transform(self, expression)
2969
2970        if isinstance(expression, int):
2971            return str(expression)
2972
2973        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
2974            escaped = expression.replace("'", "\\'")
2975            escaped = f"\\'{expression}\\'"
2976        else:
2977            escaped = expression.replace('"', '\\"')
2978            escaped = f'"{escaped}"'
2979
2980        return escaped
2981
2982    def formatjson_sql(self, expression: exp.FormatJson) -> str:
2983        return f"{self.sql(expression, 'this')} FORMAT JSON"
2984
2985    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
2986        null_handling = expression.args.get("null_handling")
2987        null_handling = f" {null_handling}" if null_handling else ""
2988
2989        unique_keys = expression.args.get("unique_keys")
2990        if unique_keys is not None:
2991            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
2992        else:
2993            unique_keys = ""
2994
2995        return_type = self.sql(expression, "return_type")
2996        return_type = f" RETURNING {return_type}" if return_type else ""
2997        encoding = self.sql(expression, "encoding")
2998        encoding = f" ENCODING {encoding}" if encoding else ""
2999
3000        return self.func(
3001            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3002            *expression.expressions,
3003            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3004        )
3005
3006    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3007        return self.jsonobject_sql(expression)
3008
3009    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3010        null_handling = expression.args.get("null_handling")
3011        null_handling = f" {null_handling}" if null_handling else ""
3012        return_type = self.sql(expression, "return_type")
3013        return_type = f" RETURNING {return_type}" if return_type else ""
3014        strict = " STRICT" if expression.args.get("strict") else ""
3015        return self.func(
3016            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3017        )
3018
3019    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3020        this = self.sql(expression, "this")
3021        order = self.sql(expression, "order")
3022        null_handling = expression.args.get("null_handling")
3023        null_handling = f" {null_handling}" if null_handling else ""
3024        return_type = self.sql(expression, "return_type")
3025        return_type = f" RETURNING {return_type}" if return_type else ""
3026        strict = " STRICT" if expression.args.get("strict") else ""
3027        return self.func(
3028            "JSON_ARRAYAGG",
3029            this,
3030            suffix=f"{order}{null_handling}{return_type}{strict})",
3031        )
3032
3033    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3034        path = self.sql(expression, "path")
3035        path = f" PATH {path}" if path else ""
3036        nested_schema = self.sql(expression, "nested_schema")
3037
3038        if nested_schema:
3039            return f"NESTED{path} {nested_schema}"
3040
3041        this = self.sql(expression, "this")
3042        kind = self.sql(expression, "kind")
3043        kind = f" {kind}" if kind else ""
3044        return f"{this}{kind}{path}"
3045
3046    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3047        return self.func("COLUMNS", *expression.expressions)
3048
3049    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3050        this = self.sql(expression, "this")
3051        path = self.sql(expression, "path")
3052        path = f", {path}" if path else ""
3053        error_handling = expression.args.get("error_handling")
3054        error_handling = f" {error_handling}" if error_handling else ""
3055        empty_handling = expression.args.get("empty_handling")
3056        empty_handling = f" {empty_handling}" if empty_handling else ""
3057        schema = self.sql(expression, "schema")
3058        return self.func(
3059            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3060        )
3061
3062    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3063        this = self.sql(expression, "this")
3064        kind = self.sql(expression, "kind")
3065        path = self.sql(expression, "path")
3066        path = f" {path}" if path else ""
3067        as_json = " AS JSON" if expression.args.get("as_json") else ""
3068        return f"{this} {kind}{path}{as_json}"
3069
3070    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3071        this = self.sql(expression, "this")
3072        path = self.sql(expression, "path")
3073        path = f", {path}" if path else ""
3074        expressions = self.expressions(expression)
3075        with_ = (
3076            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3077            if expressions
3078            else ""
3079        )
3080        return f"OPENJSON({this}{path}){with_}"
3081
3082    def in_sql(self, expression: exp.In) -> str:
3083        query = expression.args.get("query")
3084        unnest = expression.args.get("unnest")
3085        field = expression.args.get("field")
3086        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3087
3088        if query:
3089            in_sql = self.sql(query)
3090        elif unnest:
3091            in_sql = self.in_unnest_op(unnest)
3092        elif field:
3093            in_sql = self.sql(field)
3094        else:
3095            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3096
3097        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3098
3099    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3100        return f"(SELECT {self.sql(unnest)})"
3101
3102    def interval_sql(self, expression: exp.Interval) -> str:
3103        unit = self.sql(expression, "unit")
3104        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3105            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3106        unit = f" {unit}" if unit else ""
3107
3108        if self.SINGLE_STRING_INTERVAL:
3109            this = expression.this.name if expression.this else ""
3110            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3111
3112        this = self.sql(expression, "this")
3113        if this:
3114            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3115            this = f" {this}" if unwrapped else f" ({this})"
3116
3117        return f"INTERVAL{this}{unit}"
3118
3119    def return_sql(self, expression: exp.Return) -> str:
3120        return f"RETURN {self.sql(expression, 'this')}"
3121
3122    def reference_sql(self, expression: exp.Reference) -> str:
3123        this = self.sql(expression, "this")
3124        expressions = self.expressions(expression, flat=True)
3125        expressions = f"({expressions})" if expressions else ""
3126        options = self.expressions(expression, key="options", flat=True, sep=" ")
3127        options = f" {options}" if options else ""
3128        return f"REFERENCES {this}{expressions}{options}"
3129
3130    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3131        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3132        parent = expression.parent
3133        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3134        return self.func(
3135            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3136        )
3137
3138    def paren_sql(self, expression: exp.Paren) -> str:
3139        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3140        return f"({sql}{self.seg(')', sep='')}"
3141
3142    def neg_sql(self, expression: exp.Neg) -> str:
3143        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3144        this_sql = self.sql(expression, "this")
3145        sep = " " if this_sql[0] == "-" else ""
3146        return f"-{sep}{this_sql}"
3147
3148    def not_sql(self, expression: exp.Not) -> str:
3149        return f"NOT {self.sql(expression, 'this')}"
3150
3151    def alias_sql(self, expression: exp.Alias) -> str:
3152        alias = self.sql(expression, "alias")
3153        alias = f" AS {alias}" if alias else ""
3154        return f"{self.sql(expression, 'this')}{alias}"
3155
3156    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3157        alias = expression.args["alias"]
3158
3159        parent = expression.parent
3160        pivot = parent and parent.parent
3161
3162        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3163            identifier_alias = isinstance(alias, exp.Identifier)
3164            literal_alias = isinstance(alias, exp.Literal)
3165
3166            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3167                alias.replace(exp.Literal.string(alias.output_name))
3168            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3169                alias.replace(exp.to_identifier(alias.output_name))
3170
3171        return self.alias_sql(expression)
3172
3173    def aliases_sql(self, expression: exp.Aliases) -> str:
3174        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
3175
3176    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3177        this = self.sql(expression, "this")
3178        index = self.sql(expression, "expression")
3179        return f"{this} AT {index}"
3180
3181    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3182        this = self.sql(expression, "this")
3183        zone = self.sql(expression, "zone")
3184        return f"{this} AT TIME ZONE {zone}"
3185
3186    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3187        this = self.sql(expression, "this")
3188        zone = self.sql(expression, "zone")
3189        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
3190
3191    def add_sql(self, expression: exp.Add) -> str:
3192        return self.binary(expression, "+")
3193
3194    def and_sql(
3195        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3196    ) -> str:
3197        return self.connector_sql(expression, "AND", stack)
3198
3199    def or_sql(
3200        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3201    ) -> str:
3202        return self.connector_sql(expression, "OR", stack)
3203
3204    def xor_sql(
3205        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3206    ) -> str:
3207        return self.connector_sql(expression, "XOR", stack)
3208
3209    def connector_sql(
3210        self,
3211        expression: exp.Connector,
3212        op: str,
3213        stack: t.Optional[t.List[str | exp.Expression]] = None,
3214    ) -> str:
3215        if stack is not None:
3216            if expression.expressions:
3217                stack.append(self.expressions(expression, sep=f" {op} "))
3218            else:
3219                stack.append(expression.right)
3220                if expression.comments and self.comments:
3221                    for comment in expression.comments:
3222                        if comment:
3223                            op += f" /*{self.pad_comment(comment)}*/"
3224                stack.extend((op, expression.left))
3225            return op
3226
3227        stack = [expression]
3228        sqls: t.List[str] = []
3229        ops = set()
3230
3231        while stack:
3232            node = stack.pop()
3233            if isinstance(node, exp.Connector):
3234                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3235            else:
3236                sql = self.sql(node)
3237                if sqls and sqls[-1] in ops:
3238                    sqls[-1] += f" {sql}"
3239                else:
3240                    sqls.append(sql)
3241
3242        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3243        return sep.join(sqls)
3244
3245    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3246        return self.binary(expression, "&")
3247
3248    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3249        return self.binary(expression, "<<")
3250
3251    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3252        return f"~{self.sql(expression, 'this')}"
3253
3254    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3255        return self.binary(expression, "|")
3256
3257    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3258        return self.binary(expression, ">>")
3259
3260    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3261        return self.binary(expression, "^")
3262
3263    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3264        format_sql = self.sql(expression, "format")
3265        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3266        to_sql = self.sql(expression, "to")
3267        to_sql = f" {to_sql}" if to_sql else ""
3268        action = self.sql(expression, "action")
3269        action = f" {action}" if action else ""
3270        default = self.sql(expression, "default")
3271        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3272        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3273
3274    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3275        zone = self.sql(expression, "this")
3276        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
3277
3278    def collate_sql(self, expression: exp.Collate) -> str:
3279        if self.COLLATE_IS_FUNC:
3280            return self.function_fallback_sql(expression)
3281        return self.binary(expression, "COLLATE")
3282
3283    def command_sql(self, expression: exp.Command) -> str:
3284        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
3285
3286    def comment_sql(self, expression: exp.Comment) -> str:
3287        this = self.sql(expression, "this")
3288        kind = expression.args["kind"]
3289        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3290        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3291        expression_sql = self.sql(expression, "expression")
3292        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3293
3294    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3295        this = self.sql(expression, "this")
3296        delete = " DELETE" if expression.args.get("delete") else ""
3297        recompress = self.sql(expression, "recompress")
3298        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3299        to_disk = self.sql(expression, "to_disk")
3300        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3301        to_volume = self.sql(expression, "to_volume")
3302        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3303        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3304
3305    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3306        where = self.sql(expression, "where")
3307        group = self.sql(expression, "group")
3308        aggregates = self.expressions(expression, key="aggregates")
3309        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3310
3311        if not (where or group or aggregates) and len(expression.expressions) == 1:
3312            return f"TTL {self.expressions(expression, flat=True)}"
3313
3314        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3315
3316    def transaction_sql(self, expression: exp.Transaction) -> str:
3317        return "BEGIN"
3318
3319    def commit_sql(self, expression: exp.Commit) -> str:
3320        chain = expression.args.get("chain")
3321        if chain is not None:
3322            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3323
3324        return f"COMMIT{chain or ''}"
3325
3326    def rollback_sql(self, expression: exp.Rollback) -> str:
3327        savepoint = expression.args.get("savepoint")
3328        savepoint = f" TO {savepoint}" if savepoint else ""
3329        return f"ROLLBACK{savepoint}"
3330
3331    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3332        this = self.sql(expression, "this")
3333
3334        dtype = self.sql(expression, "dtype")
3335        if dtype:
3336            collate = self.sql(expression, "collate")
3337            collate = f" COLLATE {collate}" if collate else ""
3338            using = self.sql(expression, "using")
3339            using = f" USING {using}" if using else ""
3340            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
3341
3342        default = self.sql(expression, "default")
3343        if default:
3344            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3345
3346        comment = self.sql(expression, "comment")
3347        if comment:
3348            return f"ALTER COLUMN {this} COMMENT {comment}"
3349
3350        visible = expression.args.get("visible")
3351        if visible:
3352            return f"ALTER COLUMN {this} SET {visible}"
3353
3354        allow_null = expression.args.get("allow_null")
3355        drop = expression.args.get("drop")
3356
3357        if not drop and not allow_null:
3358            self.unsupported("Unsupported ALTER COLUMN syntax")
3359
3360        if allow_null is not None:
3361            keyword = "DROP" if drop else "SET"
3362            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3363
3364        return f"ALTER COLUMN {this} DROP DEFAULT"
3365
3366    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3367        this = self.sql(expression, "this")
3368
3369        visible = expression.args.get("visible")
3370        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3371
3372        return f"ALTER INDEX {this} {visible_sql}"
3373
3374    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3375        this = self.sql(expression, "this")
3376        if not isinstance(expression.this, exp.Var):
3377            this = f"KEY DISTKEY {this}"
3378        return f"ALTER DISTSTYLE {this}"
3379
3380    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3381        compound = " COMPOUND" if expression.args.get("compound") else ""
3382        this = self.sql(expression, "this")
3383        expressions = self.expressions(expression, flat=True)
3384        expressions = f"({expressions})" if expressions else ""
3385        return f"ALTER{compound} SORTKEY {this or expressions}"
3386
3387    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3388        if not self.RENAME_TABLE_WITH_DB:
3389            # Remove db from tables
3390            expression = expression.transform(
3391                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3392            ).assert_is(exp.AlterRename)
3393        this = self.sql(expression, "this")
3394        return f"RENAME TO {this}"
3395
3396    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3397        exists = " IF EXISTS" if expression.args.get("exists") else ""
3398        old_column = self.sql(expression, "this")
3399        new_column = self.sql(expression, "to")
3400        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
3401
3402    def alterset_sql(self, expression: exp.AlterSet) -> str:
3403        exprs = self.expressions(expression, flat=True)
3404        return f"SET {exprs}"
3405
3406    def alter_sql(self, expression: exp.Alter) -> str:
3407        actions = expression.args["actions"]
3408
3409        if isinstance(actions[0], exp.ColumnDef):
3410            actions = self.add_column_sql(expression)
3411        elif isinstance(actions[0], exp.Schema):
3412            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
3413        elif isinstance(actions[0], exp.Delete):
3414            actions = self.expressions(expression, key="actions", flat=True)
3415        elif isinstance(actions[0], exp.Query):
3416            actions = "AS " + self.expressions(expression, key="actions")
3417        else:
3418            actions = self.expressions(expression, key="actions", flat=True)
3419
3420        exists = " IF EXISTS" if expression.args.get("exists") else ""
3421        on_cluster = self.sql(expression, "cluster")
3422        on_cluster = f" {on_cluster}" if on_cluster else ""
3423        only = " ONLY" if expression.args.get("only") else ""
3424        options = self.expressions(expression, key="options")
3425        options = f", {options}" if options else ""
3426        kind = self.sql(expression, "kind")
3427        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3428
3429        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3430
3431    def add_column_sql(self, expression: exp.Alter) -> str:
3432        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3433            return self.expressions(
3434                expression,
3435                key="actions",
3436                prefix="ADD COLUMN ",
3437                skip_first=True,
3438            )
3439        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3440
3441    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3442        expressions = self.expressions(expression)
3443        exists = " IF EXISTS " if expression.args.get("exists") else " "
3444        return f"DROP{exists}{expressions}"
3445
3446    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3447        return f"ADD {self.expressions(expression)}"
3448
3449    def distinct_sql(self, expression: exp.Distinct) -> str:
3450        this = self.expressions(expression, flat=True)
3451
3452        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3453            case = exp.case()
3454            for arg in expression.expressions:
3455                case = case.when(arg.is_(exp.null()), exp.null())
3456            this = self.sql(case.else_(f"({this})"))
3457
3458        this = f" {this}" if this else ""
3459
3460        on = self.sql(expression, "on")
3461        on = f" ON {on}" if on else ""
3462        return f"DISTINCT{this}{on}"
3463
3464    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3465        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
3466
3467    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3468        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
3469
3470    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3471        this_sql = self.sql(expression, "this")
3472        expression_sql = self.sql(expression, "expression")
3473        kind = "MAX" if expression.args.get("max") else "MIN"
3474        return f"{this_sql} HAVING {kind} {expression_sql}"
3475
3476    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3477        return self.sql(
3478            exp.Cast(
3479                this=exp.Div(this=expression.this, expression=expression.expression),
3480                to=exp.DataType(this=exp.DataType.Type.INT),
3481            )
3482        )
3483
3484    def dpipe_sql(self, expression: exp.DPipe) -> str:
3485        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3486            return self.func(
3487                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3488            )
3489        return self.binary(expression, "||")
3490
3491    def div_sql(self, expression: exp.Div) -> str:
3492        l, r = expression.left, expression.right
3493
3494        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3495            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3496
3497        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3498            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3499                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3500
3501        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3502            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3503                return self.sql(
3504                    exp.cast(
3505                        l / r,
3506                        to=exp.DataType.Type.BIGINT,
3507                    )
3508                )
3509
3510        return self.binary(expression, "/")
3511
3512    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3513        n = exp._wrap(expression.this, exp.Binary)
3514        d = exp._wrap(expression.expression, exp.Binary)
3515        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
3516
3517    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3518        return self.binary(expression, "OVERLAPS")
3519
3520    def distance_sql(self, expression: exp.Distance) -> str:
3521        return self.binary(expression, "<->")
3522
3523    def dot_sql(self, expression: exp.Dot) -> str:
3524        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
3525
3526    def eq_sql(self, expression: exp.EQ) -> str:
3527        return self.binary(expression, "=")
3528
3529    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3530        return self.binary(expression, ":=")
3531
3532    def escape_sql(self, expression: exp.Escape) -> str:
3533        return self.binary(expression, "ESCAPE")
3534
3535    def glob_sql(self, expression: exp.Glob) -> str:
3536        return self.binary(expression, "GLOB")
3537
3538    def gt_sql(self, expression: exp.GT) -> str:
3539        return self.binary(expression, ">")
3540
3541    def gte_sql(self, expression: exp.GTE) -> str:
3542        return self.binary(expression, ">=")
3543
3544    def ilike_sql(self, expression: exp.ILike) -> str:
3545        return self.binary(expression, "ILIKE")
3546
3547    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3548        return self.binary(expression, "ILIKE ANY")
3549
3550    def is_sql(self, expression: exp.Is) -> str:
3551        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3552            return self.sql(
3553                expression.this if expression.expression.this else exp.not_(expression.this)
3554            )
3555        return self.binary(expression, "IS")
3556
3557    def like_sql(self, expression: exp.Like) -> str:
3558        return self.binary(expression, "LIKE")
3559
3560    def likeany_sql(self, expression: exp.LikeAny) -> str:
3561        return self.binary(expression, "LIKE ANY")
3562
3563    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3564        return self.binary(expression, "SIMILAR TO")
3565
3566    def lt_sql(self, expression: exp.LT) -> str:
3567        return self.binary(expression, "<")
3568
3569    def lte_sql(self, expression: exp.LTE) -> str:
3570        return self.binary(expression, "<=")
3571
3572    def mod_sql(self, expression: exp.Mod) -> str:
3573        return self.binary(expression, "%")
3574
3575    def mul_sql(self, expression: exp.Mul) -> str:
3576        return self.binary(expression, "*")
3577
3578    def neq_sql(self, expression: exp.NEQ) -> str:
3579        return self.binary(expression, "<>")
3580
3581    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3582        return self.binary(expression, "IS NOT DISTINCT FROM")
3583
3584    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3585        return self.binary(expression, "IS DISTINCT FROM")
3586
3587    def slice_sql(self, expression: exp.Slice) -> str:
3588        return self.binary(expression, ":")
3589
3590    def sub_sql(self, expression: exp.Sub) -> str:
3591        return self.binary(expression, "-")
3592
3593    def trycast_sql(self, expression: exp.TryCast) -> str:
3594        return self.cast_sql(expression, safe_prefix="TRY_")
3595
3596    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3597        return self.cast_sql(expression)
3598
3599    def try_sql(self, expression: exp.Try) -> str:
3600        if not self.TRY_SUPPORTED:
3601            self.unsupported("Unsupported TRY function")
3602            return self.sql(expression, "this")
3603
3604        return self.func("TRY", expression.this)
3605
3606    def log_sql(self, expression: exp.Log) -> str:
3607        this = expression.this
3608        expr = expression.expression
3609
3610        if self.dialect.LOG_BASE_FIRST is False:
3611            this, expr = expr, this
3612        elif self.dialect.LOG_BASE_FIRST is None and expr:
3613            if this.name in ("2", "10"):
3614                return self.func(f"LOG{this.name}", expr)
3615
3616            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3617
3618        return self.func("LOG", this, expr)
3619
3620    def use_sql(self, expression: exp.Use) -> str:
3621        kind = self.sql(expression, "kind")
3622        kind = f" {kind}" if kind else ""
3623        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3624        this = f" {this}" if this else ""
3625        return f"USE{kind}{this}"
3626
3627    def binary(self, expression: exp.Binary, op: str) -> str:
3628        sqls: t.List[str] = []
3629        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3630        binary_type = type(expression)
3631
3632        while stack:
3633            node = stack.pop()
3634
3635            if type(node) is binary_type:
3636                op_func = node.args.get("operator")
3637                if op_func:
3638                    op = f"OPERATOR({self.sql(op_func)})"
3639
3640                stack.append(node.right)
3641                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3642                stack.append(node.left)
3643            else:
3644                sqls.append(self.sql(node))
3645
3646        return "".join(sqls)
3647
3648    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3649        to_clause = self.sql(expression, "to")
3650        if to_clause:
3651            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3652
3653        return self.function_fallback_sql(expression)
3654
3655    def function_fallback_sql(self, expression: exp.Func) -> str:
3656        args = []
3657
3658        for key in expression.arg_types:
3659            arg_value = expression.args.get(key)
3660
3661            if isinstance(arg_value, list):
3662                for value in arg_value:
3663                    args.append(value)
3664            elif arg_value is not None:
3665                args.append(arg_value)
3666
3667        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3668            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3669        else:
3670            name = expression.sql_name()
3671
3672        return self.func(name, *args)
3673
3674    def func(
3675        self,
3676        name: str,
3677        *args: t.Optional[exp.Expression | str],
3678        prefix: str = "(",
3679        suffix: str = ")",
3680        normalize: bool = True,
3681    ) -> str:
3682        name = self.normalize_func(name) if normalize else name
3683        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
3684
3685    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3686        arg_sqls = tuple(
3687            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3688        )
3689        if self.pretty and self.too_wide(arg_sqls):
3690            return self.indent(
3691                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3692            )
3693        return sep.join(arg_sqls)
3694
3695    def too_wide(self, args: t.Iterable) -> bool:
3696        return sum(len(arg) for arg in args) > self.max_text_width
3697
3698    def format_time(
3699        self,
3700        expression: exp.Expression,
3701        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3702        inverse_time_trie: t.Optional[t.Dict] = None,
3703    ) -> t.Optional[str]:
3704        return format_time(
3705            self.sql(expression, "format"),
3706            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3707            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3708        )
3709
3710    def expressions(
3711        self,
3712        expression: t.Optional[exp.Expression] = None,
3713        key: t.Optional[str] = None,
3714        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3715        flat: bool = False,
3716        indent: bool = True,
3717        skip_first: bool = False,
3718        skip_last: bool = False,
3719        sep: str = ", ",
3720        prefix: str = "",
3721        dynamic: bool = False,
3722        new_line: bool = False,
3723    ) -> str:
3724        expressions = expression.args.get(key or "expressions") if expression else sqls
3725
3726        if not expressions:
3727            return ""
3728
3729        if flat:
3730            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3731
3732        num_sqls = len(expressions)
3733        result_sqls = []
3734
3735        for i, e in enumerate(expressions):
3736            sql = self.sql(e, comment=False)
3737            if not sql:
3738                continue
3739
3740            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3741
3742            if self.pretty:
3743                if self.leading_comma:
3744                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3745                else:
3746                    result_sqls.append(
3747                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3748                    )
3749            else:
3750                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3751
3752        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3753            if new_line:
3754                result_sqls.insert(0, "")
3755                result_sqls.append("")
3756            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3757        else:
3758            result_sql = "".join(result_sqls)
3759
3760        return (
3761            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3762            if indent
3763            else result_sql
3764        )
3765
3766    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3767        flat = flat or isinstance(expression.parent, exp.Properties)
3768        expressions_sql = self.expressions(expression, flat=flat)
3769        if flat:
3770            return f"{op} {expressions_sql}"
3771        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3772
3773    def naked_property(self, expression: exp.Property) -> str:
3774        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3775        if not property_name:
3776            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3777        return f"{property_name} {self.sql(expression, 'this')}"
3778
3779    def tag_sql(self, expression: exp.Tag) -> str:
3780        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
3781
3782    def token_sql(self, token_type: TokenType) -> str:
3783        return self.TOKEN_MAPPING.get(token_type, token_type.name)
3784
3785    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3786        this = self.sql(expression, "this")
3787        expressions = self.no_identify(self.expressions, expression)
3788        expressions = (
3789            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3790        )
3791        return f"{this}{expressions}" if expressions.strip() != "" else this
3792
3793    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3794        this = self.sql(expression, "this")
3795        expressions = self.expressions(expression, flat=True)
3796        return f"{this}({expressions})"
3797
3798    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3799        return self.binary(expression, "=>")
3800
3801    def when_sql(self, expression: exp.When) -> str:
3802        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3803        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3804        condition = self.sql(expression, "condition")
3805        condition = f" AND {condition}" if condition else ""
3806
3807        then_expression = expression.args.get("then")
3808        if isinstance(then_expression, exp.Insert):
3809            this = self.sql(then_expression, "this")
3810            this = f"INSERT {this}" if this else "INSERT"
3811            then = self.sql(then_expression, "expression")
3812            then = f"{this} VALUES {then}" if then else this
3813        elif isinstance(then_expression, exp.Update):
3814            if isinstance(then_expression.args.get("expressions"), exp.Star):
3815                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3816            else:
3817                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
3818        else:
3819            then = self.sql(then_expression)
3820        return f"WHEN {matched}{source}{condition} THEN {then}"
3821
3822    def whens_sql(self, expression: exp.Whens) -> str:
3823        return self.expressions(expression, sep=" ", indent=False)
3824
3825    def merge_sql(self, expression: exp.Merge) -> str:
3826        table = expression.this
3827        table_alias = ""
3828
3829        hints = table.args.get("hints")
3830        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3831            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3832            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3833
3834        this = self.sql(table)
3835        using = f"USING {self.sql(expression, 'using')}"
3836        on = f"ON {self.sql(expression, 'on')}"
3837        whens = self.sql(expression, "whens")
3838
3839        returning = self.sql(expression, "returning")
3840        if returning:
3841            whens = f"{whens}{returning}"
3842
3843        sep = self.sep()
3844
3845        return self.prepend_ctes(
3846            expression,
3847            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3848        )
3849
3850    @unsupported_args("format")
3851    def tochar_sql(self, expression: exp.ToChar) -> str:
3852        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
3853
3854    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3855        if not self.SUPPORTS_TO_NUMBER:
3856            self.unsupported("Unsupported TO_NUMBER function")
3857            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3858
3859        fmt = expression.args.get("format")
3860        if not fmt:
3861            self.unsupported("Conversion format is required for TO_NUMBER")
3862            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3863
3864        return self.func("TO_NUMBER", expression.this, fmt)
3865
3866    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3867        this = self.sql(expression, "this")
3868        kind = self.sql(expression, "kind")
3869        settings_sql = self.expressions(expression, key="settings", sep=" ")
3870        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3871        return f"{this}({kind}{args})"
3872
3873    def dictrange_sql(self, expression: exp.DictRange) -> str:
3874        this = self.sql(expression, "this")
3875        max = self.sql(expression, "max")
3876        min = self.sql(expression, "min")
3877        return f"{this}(MIN {min} MAX {max})"
3878
3879    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3880        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
3881
3882    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3883        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
3884
3885    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
3886    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3887        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
3888
3889    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
3890    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3891        expressions = self.expressions(expression, flat=True)
3892        expressions = f" {self.wrap(expressions)}" if expressions else ""
3893        buckets = self.sql(expression, "buckets")
3894        kind = self.sql(expression, "kind")
3895        buckets = f" BUCKETS {buckets}" if buckets else ""
3896        order = self.sql(expression, "order")
3897        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3898
3899    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3900        return ""
3901
3902    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3903        expressions = self.expressions(expression, key="expressions", flat=True)
3904        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3905        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3906        buckets = self.sql(expression, "buckets")
3907        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3908
3909    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3910        this = self.sql(expression, "this")
3911        having = self.sql(expression, "having")
3912
3913        if having:
3914            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3915
3916        return self.func("ANY_VALUE", this)
3917
3918    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3919        transform = self.func("TRANSFORM", *expression.expressions)
3920        row_format_before = self.sql(expression, "row_format_before")
3921        row_format_before = f" {row_format_before}" if row_format_before else ""
3922        record_writer = self.sql(expression, "record_writer")
3923        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3924        using = f" USING {self.sql(expression, 'command_script')}"
3925        schema = self.sql(expression, "schema")
3926        schema = f" AS {schema}" if schema else ""
3927        row_format_after = self.sql(expression, "row_format_after")
3928        row_format_after = f" {row_format_after}" if row_format_after else ""
3929        record_reader = self.sql(expression, "record_reader")
3930        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3931        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3932
3933    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3934        key_block_size = self.sql(expression, "key_block_size")
3935        if key_block_size:
3936            return f"KEY_BLOCK_SIZE = {key_block_size}"
3937
3938        using = self.sql(expression, "using")
3939        if using:
3940            return f"USING {using}"
3941
3942        parser = self.sql(expression, "parser")
3943        if parser:
3944            return f"WITH PARSER {parser}"
3945
3946        comment = self.sql(expression, "comment")
3947        if comment:
3948            return f"COMMENT {comment}"
3949
3950        visible = expression.args.get("visible")
3951        if visible is not None:
3952            return "VISIBLE" if visible else "INVISIBLE"
3953
3954        engine_attr = self.sql(expression, "engine_attr")
3955        if engine_attr:
3956            return f"ENGINE_ATTRIBUTE = {engine_attr}"
3957
3958        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
3959        if secondary_engine_attr:
3960            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
3961
3962        self.unsupported("Unsupported index constraint option.")
3963        return ""
3964
3965    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
3966        enforced = " ENFORCED" if expression.args.get("enforced") else ""
3967        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
3968
3969    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
3970        kind = self.sql(expression, "kind")
3971        kind = f"{kind} INDEX" if kind else "INDEX"
3972        this = self.sql(expression, "this")
3973        this = f" {this}" if this else ""
3974        index_type = self.sql(expression, "index_type")
3975        index_type = f" USING {index_type}" if index_type else ""
3976        expressions = self.expressions(expression, flat=True)
3977        expressions = f" ({expressions})" if expressions else ""
3978        options = self.expressions(expression, key="options", sep=" ")
3979        options = f" {options}" if options else ""
3980        return f"{kind}{this}{index_type}{expressions}{options}"
3981
3982    def nvl2_sql(self, expression: exp.Nvl2) -> str:
3983        if self.NVL2_SUPPORTED:
3984            return self.function_fallback_sql(expression)
3985
3986        case = exp.Case().when(
3987            expression.this.is_(exp.null()).not_(copy=False),
3988            expression.args["true"],
3989            copy=False,
3990        )
3991        else_cond = expression.args.get("false")
3992        if else_cond:
3993            case.else_(else_cond, copy=False)
3994
3995        return self.sql(case)
3996
3997    def comprehension_sql(self, expression: exp.Comprehension) -> str:
3998        this = self.sql(expression, "this")
3999        expr = self.sql(expression, "expression")
4000        iterator = self.sql(expression, "iterator")
4001        condition = self.sql(expression, "condition")
4002        condition = f" IF {condition}" if condition else ""
4003        return f"{this} FOR {expr} IN {iterator}{condition}"
4004
4005    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4006        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
4007
4008    def opclass_sql(self, expression: exp.Opclass) -> str:
4009        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
4010
4011    def predict_sql(self, expression: exp.Predict) -> str:
4012        model = self.sql(expression, "this")
4013        model = f"MODEL {model}"
4014        table = self.sql(expression, "expression")
4015        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4016        parameters = self.sql(expression, "params_struct")
4017        return self.func("PREDICT", model, table, parameters or None)
4018
4019    def forin_sql(self, expression: exp.ForIn) -> str:
4020        this = self.sql(expression, "this")
4021        expression_sql = self.sql(expression, "expression")
4022        return f"FOR {this} DO {expression_sql}"
4023
4024    def refresh_sql(self, expression: exp.Refresh) -> str:
4025        this = self.sql(expression, "this")
4026        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4027        return f"REFRESH {table}{this}"
4028
4029    def toarray_sql(self, expression: exp.ToArray) -> str:
4030        arg = expression.this
4031        if not arg.type:
4032            from sqlglot.optimizer.annotate_types import annotate_types
4033
4034            arg = annotate_types(arg, dialect=self.dialect)
4035
4036        if arg.is_type(exp.DataType.Type.ARRAY):
4037            return self.sql(arg)
4038
4039        cond_for_null = arg.is_(exp.null())
4040        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4041
4042    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4043        this = expression.this
4044        time_format = self.format_time(expression)
4045
4046        if time_format:
4047            return self.sql(
4048                exp.cast(
4049                    exp.StrToTime(this=this, format=expression.args["format"]),
4050                    exp.DataType.Type.TIME,
4051                )
4052            )
4053
4054        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4055            return self.sql(this)
4056
4057        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4058
4059    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4060        this = expression.this
4061        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4062            return self.sql(this)
4063
4064        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4065
4066    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4067        this = expression.this
4068        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4069            return self.sql(this)
4070
4071        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4072
4073    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4074        this = expression.this
4075        time_format = self.format_time(expression)
4076
4077        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4078            return self.sql(
4079                exp.cast(
4080                    exp.StrToTime(this=this, format=expression.args["format"]),
4081                    exp.DataType.Type.DATE,
4082                )
4083            )
4084
4085        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4086            return self.sql(this)
4087
4088        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4089
4090    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4091        return self.sql(
4092            exp.func(
4093                "DATEDIFF",
4094                expression.this,
4095                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4096                "day",
4097            )
4098        )
4099
4100    def lastday_sql(self, expression: exp.LastDay) -> str:
4101        if self.LAST_DAY_SUPPORTS_DATE_PART:
4102            return self.function_fallback_sql(expression)
4103
4104        unit = expression.text("unit")
4105        if unit and unit != "MONTH":
4106            self.unsupported("Date parts are not supported in LAST_DAY.")
4107
4108        return self.func("LAST_DAY", expression.this)
4109
4110    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4111        from sqlglot.dialects.dialect import unit_to_str
4112
4113        return self.func(
4114            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4115        )
4116
4117    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4118        if self.CAN_IMPLEMENT_ARRAY_ANY:
4119            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4120            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4121            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4122            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4123
4124        from sqlglot.dialects import Dialect
4125
4126        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4127        if self.dialect.__class__ != Dialect:
4128            self.unsupported("ARRAY_ANY is unsupported")
4129
4130        return self.function_fallback_sql(expression)
4131
4132    def struct_sql(self, expression: exp.Struct) -> str:
4133        expression.set(
4134            "expressions",
4135            [
4136                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4137                if isinstance(e, exp.PropertyEQ)
4138                else e
4139                for e in expression.expressions
4140            ],
4141        )
4142
4143        return self.function_fallback_sql(expression)
4144
4145    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4146        low = self.sql(expression, "this")
4147        high = self.sql(expression, "expression")
4148
4149        return f"{low} TO {high}"
4150
4151    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4152        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4153        tables = f" {self.expressions(expression)}"
4154
4155        exists = " IF EXISTS" if expression.args.get("exists") else ""
4156
4157        on_cluster = self.sql(expression, "cluster")
4158        on_cluster = f" {on_cluster}" if on_cluster else ""
4159
4160        identity = self.sql(expression, "identity")
4161        identity = f" {identity} IDENTITY" if identity else ""
4162
4163        option = self.sql(expression, "option")
4164        option = f" {option}" if option else ""
4165
4166        partition = self.sql(expression, "partition")
4167        partition = f" {partition}" if partition else ""
4168
4169        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4170
4171    # This transpiles T-SQL's CONVERT function
4172    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
4173    def convert_sql(self, expression: exp.Convert) -> str:
4174        to = expression.this
4175        value = expression.expression
4176        style = expression.args.get("style")
4177        safe = expression.args.get("safe")
4178        strict = expression.args.get("strict")
4179
4180        if not to or not value:
4181            return ""
4182
4183        # Retrieve length of datatype and override to default if not specified
4184        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4185            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4186
4187        transformed: t.Optional[exp.Expression] = None
4188        cast = exp.Cast if strict else exp.TryCast
4189
4190        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4191        if isinstance(style, exp.Literal) and style.is_int:
4192            from sqlglot.dialects.tsql import TSQL
4193
4194            style_value = style.name
4195            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4196            if not converted_style:
4197                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4198
4199            fmt = exp.Literal.string(converted_style)
4200
4201            if to.this == exp.DataType.Type.DATE:
4202                transformed = exp.StrToDate(this=value, format=fmt)
4203            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4204                transformed = exp.StrToTime(this=value, format=fmt)
4205            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4206                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4207            elif to.this == exp.DataType.Type.TEXT:
4208                transformed = exp.TimeToStr(this=value, format=fmt)
4209
4210        if not transformed:
4211            transformed = cast(this=value, to=to, safe=safe)
4212
4213        return self.sql(transformed)
4214
4215    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
4216        this = expression.this
4217        if isinstance(this, exp.JSONPathWildcard):
4218            this = self.json_path_part(this)
4219            return f".{this}" if this else ""
4220
4221        if exp.SAFE_IDENTIFIER_RE.match(this):
4222            return f".{this}"
4223
4224        this = self.json_path_part(this)
4225        return (
4226            f"[{this}]"
4227            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
4228            else f".{this}"
4229        )
4230
4231    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
4232        this = self.json_path_part(expression.this)
4233        return f"[{this}]" if this else ""
4234
4235    def _simplify_unless_literal(self, expression: E) -> E:
4236        if not isinstance(expression, exp.Literal):
4237            from sqlglot.optimizer.simplify import simplify
4238
4239            expression = simplify(expression, dialect=self.dialect)
4240
4241        return expression
4242
4243    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
4244        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
4245            # The first modifier here will be the one closest to the AggFunc's arg
4246            mods = sorted(
4247                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
4248                key=lambda x: 0
4249                if isinstance(x, exp.HavingMax)
4250                else (1 if isinstance(x, exp.Order) else 2),
4251            )
4252
4253            if mods:
4254                mod = mods[0]
4255                this = expression.__class__(this=mod.this.copy())
4256                this.meta["inline"] = True
4257                mod.this.replace(this)
4258                return self.sql(expression.this)
4259
4260            agg_func = expression.find(exp.AggFunc)
4261
4262            if agg_func:
4263                return self.sql(agg_func)[:-1] + f" {text})"
4264
4265        return f"{self.sql(expression, 'this')} {text}"
4266
4267    def _replace_line_breaks(self, string: str) -> str:
4268        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
4269        if self.pretty:
4270            return string.replace("\n", self.SENTINEL_LINE_BREAK)
4271        return string
4272
4273    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4274        option = self.sql(expression, "this")
4275
4276        if expression.expressions:
4277            upper = option.upper()
4278
4279            # Snowflake FILE_FORMAT options are separated by whitespace
4280            sep = " " if upper == "FILE_FORMAT" else ", "
4281
4282            # Databricks copy/format options do not set their list of values with EQ
4283            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4284            values = self.expressions(expression, flat=True, sep=sep)
4285            return f"{option}{op}({values})"
4286
4287        value = self.sql(expression, "expression")
4288
4289        if not value:
4290            return option
4291
4292        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4293
4294        return f"{option}{op}{value}"
4295
4296    def credentials_sql(self, expression: exp.Credentials) -> str:
4297        cred_expr = expression.args.get("credentials")
4298        if isinstance(cred_expr, exp.Literal):
4299            # Redshift case: CREDENTIALS <string>
4300            credentials = self.sql(expression, "credentials")
4301            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4302        else:
4303            # Snowflake case: CREDENTIALS = (...)
4304            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4305            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4306
4307        storage = self.sql(expression, "storage")
4308        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4309
4310        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4311        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4312
4313        iam_role = self.sql(expression, "iam_role")
4314        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4315
4316        region = self.sql(expression, "region")
4317        region = f" REGION {region}" if region else ""
4318
4319        return f"{credentials}{storage}{encryption}{iam_role}{region}"
4320
4321    def copy_sql(self, expression: exp.Copy) -> str:
4322        this = self.sql(expression, "this")
4323        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4324
4325        credentials = self.sql(expression, "credentials")
4326        credentials = self.seg(credentials) if credentials else ""
4327        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4328        files = self.expressions(expression, key="files", flat=True)
4329
4330        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4331        params = self.expressions(
4332            expression,
4333            key="params",
4334            sep=sep,
4335            new_line=True,
4336            skip_last=True,
4337            skip_first=True,
4338            indent=self.COPY_PARAMS_ARE_WRAPPED,
4339        )
4340
4341        if params:
4342            if self.COPY_PARAMS_ARE_WRAPPED:
4343                params = f" WITH ({params})"
4344            elif not self.pretty:
4345                params = f" {params}"
4346
4347        return f"COPY{this}{kind} {files}{credentials}{params}"
4348
4349    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4350        return ""
4351
4352    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4353        on_sql = "ON" if expression.args.get("on") else "OFF"
4354        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4355        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4356        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4357        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4358
4359        if filter_col or retention_period:
4360            on_sql = self.func("ON", filter_col, retention_period)
4361
4362        return f"DATA_DELETION={on_sql}"
4363
4364    def maskingpolicycolumnconstraint_sql(
4365        self, expression: exp.MaskingPolicyColumnConstraint
4366    ) -> str:
4367        this = self.sql(expression, "this")
4368        expressions = self.expressions(expression, flat=True)
4369        expressions = f" USING ({expressions})" if expressions else ""
4370        return f"MASKING POLICY {this}{expressions}"
4371
4372    def gapfill_sql(self, expression: exp.GapFill) -> str:
4373        this = self.sql(expression, "this")
4374        this = f"TABLE {this}"
4375        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
4376
4377    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4378        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
4379
4380    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4381        this = self.sql(expression, "this")
4382        expr = expression.expression
4383
4384        if isinstance(expr, exp.Func):
4385            # T-SQL's CLR functions are case sensitive
4386            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4387        else:
4388            expr = self.sql(expression, "expression")
4389
4390        return self.scope_resolution(expr, this)
4391
4392    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4393        if self.PARSE_JSON_NAME is None:
4394            return self.sql(expression.this)
4395
4396        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
4397
4398    def rand_sql(self, expression: exp.Rand) -> str:
4399        lower = self.sql(expression, "lower")
4400        upper = self.sql(expression, "upper")
4401
4402        if lower and upper:
4403            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4404        return self.func("RAND", expression.this)
4405
4406    def changes_sql(self, expression: exp.Changes) -> str:
4407        information = self.sql(expression, "information")
4408        information = f"INFORMATION => {information}"
4409        at_before = self.sql(expression, "at_before")
4410        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4411        end = self.sql(expression, "end")
4412        end = f"{self.seg('')}{end}" if end else ""
4413
4414        return f"CHANGES ({information}){at_before}{end}"
4415
4416    def pad_sql(self, expression: exp.Pad) -> str:
4417        prefix = "L" if expression.args.get("is_left") else "R"
4418
4419        fill_pattern = self.sql(expression, "fill_pattern") or None
4420        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4421            fill_pattern = "' '"
4422
4423        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
4424
4425    def summarize_sql(self, expression: exp.Summarize) -> str:
4426        table = " TABLE" if expression.args.get("table") else ""
4427        return f"SUMMARIZE{table} {self.sql(expression.this)}"
4428
4429    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4430        generate_series = exp.GenerateSeries(**expression.args)
4431
4432        parent = expression.parent
4433        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4434            parent = parent.parent
4435
4436        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4437            return self.sql(exp.Unnest(expressions=[generate_series]))
4438
4439        if isinstance(parent, exp.Select):
4440            self.unsupported("GenerateSeries projection unnesting is not supported.")
4441
4442        return self.sql(generate_series)
4443
4444    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4445        exprs = expression.expressions
4446        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4447            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4448        else:
4449            rhs = self.expressions(expression)
4450
4451        return self.func(name, expression.this, rhs or None)
4452
4453    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4454        if self.SUPPORTS_CONVERT_TIMEZONE:
4455            return self.function_fallback_sql(expression)
4456
4457        source_tz = expression.args.get("source_tz")
4458        target_tz = expression.args.get("target_tz")
4459        timestamp = expression.args.get("timestamp")
4460
4461        if source_tz and timestamp:
4462            timestamp = exp.AtTimeZone(
4463                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4464            )
4465
4466        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4467
4468        return self.sql(expr)
4469
4470    def json_sql(self, expression: exp.JSON) -> str:
4471        this = self.sql(expression, "this")
4472        this = f" {this}" if this else ""
4473
4474        _with = expression.args.get("with")
4475
4476        if _with is None:
4477            with_sql = ""
4478        elif not _with:
4479            with_sql = " WITHOUT"
4480        else:
4481            with_sql = " WITH"
4482
4483        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4484
4485        return f"JSON{this}{with_sql}{unique_sql}"
4486
4487    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4488        def _generate_on_options(arg: t.Any) -> str:
4489            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4490
4491        path = self.sql(expression, "path")
4492        returning = self.sql(expression, "returning")
4493        returning = f" RETURNING {returning}" if returning else ""
4494
4495        on_condition = self.sql(expression, "on_condition")
4496        on_condition = f" {on_condition}" if on_condition else ""
4497
4498        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4499
4500    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4501        else_ = "ELSE " if expression.args.get("else_") else ""
4502        condition = self.sql(expression, "expression")
4503        condition = f"WHEN {condition} THEN " if condition else else_
4504        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4505        return f"{condition}{insert}"
4506
4507    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4508        kind = self.sql(expression, "kind")
4509        expressions = self.seg(self.expressions(expression, sep=" "))
4510        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4511        return res
4512
4513    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4514        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4515        empty = expression.args.get("empty")
4516        empty = (
4517            f"DEFAULT {empty} ON EMPTY"
4518            if isinstance(empty, exp.Expression)
4519            else self.sql(expression, "empty")
4520        )
4521
4522        error = expression.args.get("error")
4523        error = (
4524            f"DEFAULT {error} ON ERROR"
4525            if isinstance(error, exp.Expression)
4526            else self.sql(expression, "error")
4527        )
4528
4529        if error and empty:
4530            error = (
4531                f"{empty} {error}"
4532                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4533                else f"{error} {empty}"
4534            )
4535            empty = ""
4536
4537        null = self.sql(expression, "null")
4538
4539        return f"{empty}{error}{null}"
4540
4541    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4542        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4543        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
4544
4545    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4546        this = self.sql(expression, "this")
4547        path = self.sql(expression, "path")
4548
4549        passing = self.expressions(expression, "passing")
4550        passing = f" PASSING {passing}" if passing else ""
4551
4552        on_condition = self.sql(expression, "on_condition")
4553        on_condition = f" {on_condition}" if on_condition else ""
4554
4555        path = f"{path}{passing}{on_condition}"
4556
4557        return self.func("JSON_EXISTS", this, path)
4558
4559    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4560        array_agg = self.function_fallback_sql(expression)
4561
4562        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4563        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4564        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4565            parent = expression.parent
4566            if isinstance(parent, exp.Filter):
4567                parent_cond = parent.expression.this
4568                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4569            else:
4570                this = expression.this
4571                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4572                if this.find(exp.Column):
4573                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4574                    this_sql = (
4575                        self.expressions(this)
4576                        if isinstance(this, exp.Distinct)
4577                        else self.sql(expression, "this")
4578                    )
4579
4580                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4581
4582        return array_agg
4583
4584    def apply_sql(self, expression: exp.Apply) -> str:
4585        this = self.sql(expression, "this")
4586        expr = self.sql(expression, "expression")
4587
4588        return f"{this} APPLY({expr})"
4589
4590    def grant_sql(self, expression: exp.Grant) -> str:
4591        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4592
4593        kind = self.sql(expression, "kind")
4594        kind = f" {kind}" if kind else ""
4595
4596        securable = self.sql(expression, "securable")
4597        securable = f" {securable}" if securable else ""
4598
4599        principals = self.expressions(expression, key="principals", flat=True)
4600
4601        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4602
4603        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4604
4605    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4606        this = self.sql(expression, "this")
4607        columns = self.expressions(expression, flat=True)
4608        columns = f"({columns})" if columns else ""
4609
4610        return f"{this}{columns}"
4611
4612    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4613        this = self.sql(expression, "this")
4614
4615        kind = self.sql(expression, "kind")
4616        kind = f"{kind} " if kind else ""
4617
4618        return f"{kind}{this}"
4619
4620    def columns_sql(self, expression: exp.Columns):
4621        func = self.function_fallback_sql(expression)
4622        if expression.args.get("unpack"):
4623            func = f"*{func}"
4624
4625        return func
4626
4627    def overlay_sql(self, expression: exp.Overlay):
4628        this = self.sql(expression, "this")
4629        expr = self.sql(expression, "expression")
4630        from_sql = self.sql(expression, "from")
4631        for_sql = self.sql(expression, "for")
4632        for_sql = f" FOR {for_sql}" if for_sql else ""
4633
4634        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
4635
4636    @unsupported_args("format")
4637    def todouble_sql(self, expression: exp.ToDouble) -> str:
4638        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
4639
4640    def string_sql(self, expression: exp.String) -> str:
4641        this = expression.this
4642        zone = expression.args.get("zone")
4643
4644        if zone:
4645            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4646            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4647            # set for source_tz to transpile the time conversion before the STRING cast
4648            this = exp.ConvertTimezone(
4649                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4650            )
4651
4652        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
4653
4654    def median_sql(self, expression: exp.Median):
4655        if not self.SUPPORTS_MEDIAN:
4656            return self.sql(
4657                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4658            )
4659
4660        return self.function_fallback_sql(expression)
4661
4662    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4663        filler = self.sql(expression, "this")
4664        filler = f" {filler}" if filler else ""
4665        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4666        return f"TRUNCATE{filler} {with_count}"
4667
4668    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4669        if self.SUPPORTS_UNIX_SECONDS:
4670            return self.function_fallback_sql(expression)
4671
4672        start_ts = exp.cast(
4673            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4674        )
4675
4676        return self.sql(
4677            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4678        )
4679
4680    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4681        dim = expression.expression
4682
4683        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4684        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4685            if not (dim.is_int and dim.name == "1"):
4686                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4687            dim = None
4688
4689        # If dimension is required but not specified, default initialize it
4690        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4691            dim = exp.Literal.number(1)
4692
4693        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4694
4695    def attach_sql(self, expression: exp.Attach) -> str:
4696        this = self.sql(expression, "this")
4697        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4698        expressions = self.expressions(expression)
4699        expressions = f" ({expressions})" if expressions else ""
4700
4701        return f"ATTACH{exists_sql} {this}{expressions}"
4702
4703    def detach_sql(self, expression: exp.Detach) -> str:
4704        this = self.sql(expression, "this")
4705        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4706
4707        return f"DETACH{exists_sql} {this}"
4708
4709    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4710        this = self.sql(expression, "this")
4711        value = self.sql(expression, "expression")
4712        value = f" {value}" if value else ""
4713        return f"{this}{value}"
4714
4715    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4716        this_sql = self.sql(expression, "this")
4717        if isinstance(expression.this, exp.Table):
4718            this_sql = f"TABLE {this_sql}"
4719
4720        return self.func(
4721            "FEATURES_AT_TIME",
4722            this_sql,
4723            expression.args.get("time"),
4724            expression.args.get("num_rows"),
4725            expression.args.get("ignore_feature_nulls"),
4726        )
4727
4728    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4729        return (
4730            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4731        )
4732
4733    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4734        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4735        encode = f"{encode} {self.sql(expression, 'this')}"
4736
4737        properties = expression.args.get("properties")
4738        if properties:
4739            encode = f"{encode} {self.properties(properties)}"
4740
4741        return encode
4742
4743    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4744        this = self.sql(expression, "this")
4745        include = f"INCLUDE {this}"
4746
4747        column_def = self.sql(expression, "column_def")
4748        if column_def:
4749            include = f"{include} {column_def}"
4750
4751        alias = self.sql(expression, "alias")
4752        if alias:
4753            include = f"{include} AS {alias}"
4754
4755        return include
4756
4757    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4758        name = f"NAME {self.sql(expression, 'this')}"
4759        return self.func("XMLELEMENT", name, *expression.expressions)
4760
4761    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4762        partitions = self.expressions(expression, "partition_expressions")
4763        create = self.expressions(expression, "create_expressions")
4764        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
4765
4766    def partitionbyrangepropertydynamic_sql(
4767        self, expression: exp.PartitionByRangePropertyDynamic
4768    ) -> str:
4769        start = self.sql(expression, "start")
4770        end = self.sql(expression, "end")
4771
4772        every = expression.args["every"]
4773        if isinstance(every, exp.Interval) and every.this.is_string:
4774            every.this.replace(exp.Literal.number(every.name))
4775
4776        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4777
4778    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4779        name = self.sql(expression, "this")
4780        values = self.expressions(expression, flat=True)
4781
4782        return f"NAME {name} VALUE {values}"
4783
4784    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4785        kind = self.sql(expression, "kind")
4786        sample = self.sql(expression, "sample")
4787        return f"SAMPLE {sample} {kind}"
4788
4789    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4790        kind = self.sql(expression, "kind")
4791        option = self.sql(expression, "option")
4792        option = f" {option}" if option else ""
4793        this = self.sql(expression, "this")
4794        this = f" {this}" if this else ""
4795        columns = self.expressions(expression)
4796        columns = f" {columns}" if columns else ""
4797        return f"{kind}{option} STATISTICS{this}{columns}"
4798
4799    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4800        this = self.sql(expression, "this")
4801        columns = self.expressions(expression)
4802        inner_expression = self.sql(expression, "expression")
4803        inner_expression = f" {inner_expression}" if inner_expression else ""
4804        update_options = self.sql(expression, "update_options")
4805        update_options = f" {update_options} UPDATE" if update_options else ""
4806        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
4807
4808    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4809        kind = self.sql(expression, "kind")
4810        kind = f" {kind}" if kind else ""
4811        return f"DELETE{kind} STATISTICS"
4812
4813    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4814        inner_expression = self.sql(expression, "expression")
4815        return f"LIST CHAINED ROWS{inner_expression}"
4816
4817    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4818        kind = self.sql(expression, "kind")
4819        this = self.sql(expression, "this")
4820        this = f" {this}" if this else ""
4821        inner_expression = self.sql(expression, "expression")
4822        return f"VALIDATE {kind}{this}{inner_expression}"
4823
4824    def analyze_sql(self, expression: exp.Analyze) -> str:
4825        options = self.expressions(expression, key="options", sep=" ")
4826        options = f" {options}" if options else ""
4827        kind = self.sql(expression, "kind")
4828        kind = f" {kind}" if kind else ""
4829        this = self.sql(expression, "this")
4830        this = f" {this}" if this else ""
4831        mode = self.sql(expression, "mode")
4832        mode = f" {mode}" if mode else ""
4833        properties = self.sql(expression, "properties")
4834        properties = f" {properties}" if properties else ""
4835        partition = self.sql(expression, "partition")
4836        partition = f" {partition}" if partition else ""
4837        inner_expression = self.sql(expression, "expression")
4838        inner_expression = f" {inner_expression}" if inner_expression else ""
4839        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4840
4841    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4842        this = self.sql(expression, "this")
4843        namespaces = self.expressions(expression, key="namespaces")
4844        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4845        passing = self.expressions(expression, key="passing")
4846        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4847        columns = self.expressions(expression, key="columns")
4848        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4849        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4850        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4851
4852    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4853        this = self.sql(expression, "this")
4854        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
4855
4856    def export_sql(self, expression: exp.Export) -> str:
4857        this = self.sql(expression, "this")
4858        connection = self.sql(expression, "connection")
4859        connection = f"WITH CONNECTION {connection} " if connection else ""
4860        options = self.sql(expression, "options")
4861        return f"EXPORT DATA {connection}{options} AS {this}"
4862
4863    def declare_sql(self, expression: exp.Declare) -> str:
4864        return f"DECLARE {self.expressions(expression, flat=True)}"
4865
4866    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4867        variable = self.sql(expression, "this")
4868        default = self.sql(expression, "default")
4869        default = f" = {default}" if default else ""
4870
4871        kind = self.sql(expression, "kind")
4872        if isinstance(expression.args.get("kind"), exp.Schema):
4873            kind = f"TABLE {kind}"
4874
4875        return f"{variable} AS {kind}{default}"
4876
4877    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4878        kind = self.sql(expression, "kind")
4879        this = self.sql(expression, "this")
4880        set = self.sql(expression, "expression")
4881        using = self.sql(expression, "using")
4882        using = f" USING {using}" if using else ""
4883
4884        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4885
4886        return f"{kind_sql} {this} SET {set}{using}"
4887
4888    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4889        params = self.expressions(expression, key="params", flat=True)
4890        return self.func(expression.name, *expression.expressions) + f"({params})"
4891
4892    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4893        return self.func(expression.name, *expression.expressions)
4894
4895    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4896        return self.anonymousaggfunc_sql(expression)
4897
4898    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4899        return self.parameterizedagg_sql(expression)
4900
4901    def show_sql(self, expression: exp.Show) -> str:
4902        self.unsupported("Unsupported SHOW statement")
4903        return ""
4904
4905    def put_sql(self, expression: exp.Put) -> str:
4906        props = expression.args.get("properties")
4907        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4908        this = self.sql(expression, "this")
4909        target = self.sql(expression, "target")
4910        return f"PUT {this} {target}{props_sql}"

Generator converts a given syntax tree to the corresponding SQL string.

Arguments:
  • pretty: Whether to format the produced SQL string. Default: False.
  • identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
  • normalize: Whether to normalize identifiers to lowercase. Default: False.
  • pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
  • indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a WHERE clause. Default: 2.
  • normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
  • unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
  • max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
  • leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
  • max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
  • comments: Whether to preserve comments in the output SQL code. Default: True
Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None)
685    def __init__(
686        self,
687        pretty: t.Optional[bool] = None,
688        identify: str | bool = False,
689        normalize: bool = False,
690        pad: int = 2,
691        indent: int = 2,
692        normalize_functions: t.Optional[str | bool] = None,
693        unsupported_level: ErrorLevel = ErrorLevel.WARN,
694        max_unsupported: int = 3,
695        leading_comma: bool = False,
696        max_text_width: int = 80,
697        comments: bool = True,
698        dialect: DialectType = None,
699    ):
700        import sqlglot
701        from sqlglot.dialects import Dialect
702
703        self.pretty = pretty if pretty is not None else sqlglot.pretty
704        self.identify = identify
705        self.normalize = normalize
706        self.pad = pad
707        self._indent = indent
708        self.unsupported_level = unsupported_level
709        self.max_unsupported = max_unsupported
710        self.leading_comma = leading_comma
711        self.max_text_width = max_text_width
712        self.comments = comments
713        self.dialect = Dialect.get_or_raise(dialect)
714
715        # This is both a Dialect property and a Generator argument, so we prioritize the latter
716        self.normalize_functions = (
717            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
718        )
719
720        self.unsupported_messages: t.List[str] = []
721        self._escaped_quote_end: str = (
722            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
723        )
724        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
725
726        self._next_name = name_sequence("_t")
727
728        self._identifier_start = self.dialect.IDENTIFIER_START
729        self._identifier_end = self.dialect.IDENTIFIER_END
730
731        self._quote_json_path_key_using_brackets = True
TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_MEDIAN = True
SUPPORTS_UNIX_SECONDS = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ALTER_SET_TYPE = 'SET DATA TYPE'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str:
733    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
734        """
735        Generates the SQL string corresponding to the given syntax tree.
736
737        Args:
738            expression: The syntax tree.
739            copy: Whether to copy the expression. The generator performs mutations so
740                it is safer to copy.
741
742        Returns:
743            The SQL string corresponding to `expression`.
744        """
745        if copy:
746            expression = expression.copy()
747
748        expression = self.preprocess(expression)
749
750        self.unsupported_messages = []
751        sql = self.sql(expression).strip()
752
753        if self.pretty:
754            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
755
756        if self.unsupported_level == ErrorLevel.IGNORE:
757            return sql
758
759        if self.unsupported_level == ErrorLevel.WARN:
760            for msg in self.unsupported_messages:
761                logger.warning(msg)
762        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
763            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
764
765        return sql

Generates the SQL string corresponding to the given syntax tree.

Arguments:
  • expression: The syntax tree.
  • copy: Whether to copy the expression. The generator performs mutations so it is safer to copy.
Returns:

The SQL string corresponding to expression.

def preprocess( self, expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression:
767    def preprocess(self, expression: exp.Expression) -> exp.Expression:
768        """Apply generic preprocessing transformations to a given expression."""
769        expression = self._move_ctes_to_top_level(expression)
770
771        if self.ENSURE_BOOLS:
772            from sqlglot.transforms import ensure_bools
773
774            expression = ensure_bools(expression)
775
776        return expression

Apply generic preprocessing transformations to a given expression.

def unsupported(self, message: str) -> None:
789    def unsupported(self, message: str) -> None:
790        if self.unsupported_level == ErrorLevel.IMMEDIATE:
791            raise UnsupportedError(message)
792        self.unsupported_messages.append(message)
def sep(self, sep: str = ' ') -> str:
794    def sep(self, sep: str = " ") -> str:
795        return f"{sep.strip()}\n" if self.pretty else sep
def seg(self, sql: str, sep: str = ' ') -> str:
797    def seg(self, sql: str, sep: str = " ") -> str:
798        return f"{self.sep(sep)}{sql}"
def pad_comment(self, comment: str) -> str:
800    def pad_comment(self, comment: str) -> str:
801        comment = " " + comment if comment[0].strip() else comment
802        comment = comment + " " if comment[-1].strip() else comment
803        return comment
def maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
805    def maybe_comment(
806        self,
807        sql: str,
808        expression: t.Optional[exp.Expression] = None,
809        comments: t.Optional[t.List[str]] = None,
810        separated: bool = False,
811    ) -> str:
812        comments = (
813            ((expression and expression.comments) if comments is None else comments)  # type: ignore
814            if self.comments
815            else None
816        )
817
818        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
819            return sql
820
821        comments_sql = " ".join(
822            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
823        )
824
825        if not comments_sql:
826            return sql
827
828        comments_sql = self._replace_line_breaks(comments_sql)
829
830        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
831            return (
832                f"{self.sep()}{comments_sql}{sql}"
833                if not sql or sql[0].isspace()
834                else f"{comments_sql}{self.sep()}{sql}"
835            )
836
837        return f"{sql} {comments_sql}"
def wrap(self, expression: sqlglot.expressions.Expression | str) -> str:
839    def wrap(self, expression: exp.Expression | str) -> str:
840        this_sql = (
841            self.sql(expression)
842            if isinstance(expression, exp.UNWRAPPED_QUERIES)
843            else self.sql(expression, "this")
844        )
845        if not this_sql:
846            return "()"
847
848        this_sql = self.indent(this_sql, level=1, pad=0)
849        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def no_identify(self, func: Callable[..., str], *args, **kwargs) -> str:
851    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
852        original = self.identify
853        self.identify = False
854        result = func(*args, **kwargs)
855        self.identify = original
856        return result
def normalize_func(self, name: str) -> str:
858    def normalize_func(self, name: str) -> str:
859        if self.normalize_functions == "upper" or self.normalize_functions is True:
860            return name.upper()
861        if self.normalize_functions == "lower":
862            return name.lower()
863        return name
def indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str:
865    def indent(
866        self,
867        sql: str,
868        level: int = 0,
869        pad: t.Optional[int] = None,
870        skip_first: bool = False,
871        skip_last: bool = False,
872    ) -> str:
873        if not self.pretty or not sql:
874            return sql
875
876        pad = self.pad if pad is None else pad
877        lines = sql.split("\n")
878
879        return "\n".join(
880            (
881                line
882                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
883                else f"{' ' * (level * self._indent + pad)}{line}"
884            )
885            for i, line in enumerate(lines)
886        )
def sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
888    def sql(
889        self,
890        expression: t.Optional[str | exp.Expression],
891        key: t.Optional[str] = None,
892        comment: bool = True,
893    ) -> str:
894        if not expression:
895            return ""
896
897        if isinstance(expression, str):
898            return expression
899
900        if key:
901            value = expression.args.get(key)
902            if value:
903                return self.sql(value)
904            return ""
905
906        transform = self.TRANSFORMS.get(expression.__class__)
907
908        if callable(transform):
909            sql = transform(self, expression)
910        elif isinstance(expression, exp.Expression):
911            exp_handler_name = f"{expression.key}_sql"
912
913            if hasattr(self, exp_handler_name):
914                sql = getattr(self, exp_handler_name)(expression)
915            elif isinstance(expression, exp.Func):
916                sql = self.function_fallback_sql(expression)
917            elif isinstance(expression, exp.Property):
918                sql = self.property_sql(expression)
919            else:
920                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
921        else:
922            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
923
924        return self.maybe_comment(sql, expression) if self.comments and comment else sql
def uncache_sql(self, expression: sqlglot.expressions.Uncache) -> str:
926    def uncache_sql(self, expression: exp.Uncache) -> str:
927        table = self.sql(expression, "this")
928        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
929        return f"UNCACHE TABLE{exists_sql} {table}"
def cache_sql(self, expression: sqlglot.expressions.Cache) -> str:
931    def cache_sql(self, expression: exp.Cache) -> str:
932        lazy = " LAZY" if expression.args.get("lazy") else ""
933        table = self.sql(expression, "this")
934        options = expression.args.get("options")
935        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
936        sql = self.sql(expression, "expression")
937        sql = f" AS{self.sep()}{sql}" if sql else ""
938        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
939        return self.prepend_ctes(expression, sql)
def characterset_sql(self, expression: sqlglot.expressions.CharacterSet) -> str:
941    def characterset_sql(self, expression: exp.CharacterSet) -> str:
942        if isinstance(expression.parent, exp.Cast):
943            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
944        default = "DEFAULT " if expression.args.get("default") else ""
945        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
def column_parts(self, expression: sqlglot.expressions.Column) -> str:
947    def column_parts(self, expression: exp.Column) -> str:
948        return ".".join(
949            self.sql(part)
950            for part in (
951                expression.args.get("catalog"),
952                expression.args.get("db"),
953                expression.args.get("table"),
954                expression.args.get("this"),
955            )
956            if part
957        )
def column_sql(self, expression: sqlglot.expressions.Column) -> str:
959    def column_sql(self, expression: exp.Column) -> str:
960        join_mark = " (+)" if expression.args.get("join_mark") else ""
961
962        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
963            join_mark = ""
964            self.unsupported("Outer join syntax using the (+) operator is not supported.")
965
966        return f"{self.column_parts(expression)}{join_mark}"
def columnposition_sql(self, expression: sqlglot.expressions.ColumnPosition) -> str:
968    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
969        this = self.sql(expression, "this")
970        this = f" {this}" if this else ""
971        position = self.sql(expression, "position")
972        return f"{position}{this}"
def columndef_sql(self, expression: sqlglot.expressions.ColumnDef, sep: str = ' ') -> str:
974    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
975        column = self.sql(expression, "this")
976        kind = self.sql(expression, "kind")
977        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
978        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
979        kind = f"{sep}{kind}" if kind else ""
980        constraints = f" {constraints}" if constraints else ""
981        position = self.sql(expression, "position")
982        position = f" {position}" if position else ""
983
984        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
985            kind = ""
986
987        return f"{exists}{column}{kind}{constraints}{position}"
def columnconstraint_sql(self, expression: sqlglot.expressions.ColumnConstraint) -> str:
989    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
990        this = self.sql(expression, "this")
991        kind_sql = self.sql(expression, "kind").strip()
992        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
def computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
 994    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
 995        this = self.sql(expression, "this")
 996        if expression.args.get("not_null"):
 997            persisted = " PERSISTED NOT NULL"
 998        elif expression.args.get("persisted"):
 999            persisted = " PERSISTED"
1000        else:
1001            persisted = ""
1002        return f"AS {this}{persisted}"
def autoincrementcolumnconstraint_sql(self, _) -> str:
1004    def autoincrementcolumnconstraint_sql(self, _) -> str:
1005        return self.token_sql(TokenType.AUTO_INCREMENT)
def compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
1007    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1008        if isinstance(expression.this, list):
1009            this = self.wrap(self.expressions(expression, key="this", flat=True))
1010        else:
1011            this = self.sql(expression, "this")
1012
1013        return f"COMPRESS {this}"
def generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1015    def generatedasidentitycolumnconstraint_sql(
1016        self, expression: exp.GeneratedAsIdentityColumnConstraint
1017    ) -> str:
1018        this = ""
1019        if expression.this is not None:
1020            on_null = " ON NULL" if expression.args.get("on_null") else ""
1021            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1022
1023        start = expression.args.get("start")
1024        start = f"START WITH {start}" if start else ""
1025        increment = expression.args.get("increment")
1026        increment = f" INCREMENT BY {increment}" if increment else ""
1027        minvalue = expression.args.get("minvalue")
1028        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1029        maxvalue = expression.args.get("maxvalue")
1030        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1031        cycle = expression.args.get("cycle")
1032        cycle_sql = ""
1033
1034        if cycle is not None:
1035            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1036            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1037
1038        sequence_opts = ""
1039        if start or increment or cycle_sql:
1040            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1041            sequence_opts = f" ({sequence_opts.strip()})"
1042
1043        expr = self.sql(expression, "expression")
1044        expr = f"({expr})" if expr else "IDENTITY"
1045
1046        return f"GENERATED{this} AS {expr}{sequence_opts}"
def generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1048    def generatedasrowcolumnconstraint_sql(
1049        self, expression: exp.GeneratedAsRowColumnConstraint
1050    ) -> str:
1051        start = "START" if expression.args.get("start") else "END"
1052        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1053        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str:
1055    def periodforsystemtimeconstraint_sql(
1056        self, expression: exp.PeriodForSystemTimeConstraint
1057    ) -> str:
1058        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
def notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str:
1060    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1061        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
def transformcolumnconstraint_sql(self, expression: sqlglot.expressions.TransformColumnConstraint) -> str:
1063    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
1064        return f"AS {self.sql(expression, 'this')}"
def primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str:
1066    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1067        desc = expression.args.get("desc")
1068        if desc is not None:
1069            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1070        options = self.expressions(expression, key="options", flat=True, sep=" ")
1071        options = f" {options}" if options else ""
1072        return f"PRIMARY KEY{options}"
def uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1074    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1075        this = self.sql(expression, "this")
1076        this = f" {this}" if this else ""
1077        index_type = expression.args.get("index_type")
1078        index_type = f" USING {index_type}" if index_type else ""
1079        on_conflict = self.sql(expression, "on_conflict")
1080        on_conflict = f" {on_conflict}" if on_conflict else ""
1081        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1082        options = self.expressions(expression, key="options", flat=True, sep=" ")
1083        options = f" {options}" if options else ""
1084        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
1086    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1087        return self.sql(expression, "this")
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
1089    def create_sql(self, expression: exp.Create) -> str:
1090        kind = self.sql(expression, "kind")
1091        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1092        properties = expression.args.get("properties")
1093        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1094
1095        this = self.createable_sql(expression, properties_locs)
1096
1097        properties_sql = ""
1098        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1099            exp.Properties.Location.POST_WITH
1100        ):
1101            properties_sql = self.sql(
1102                exp.Properties(
1103                    expressions=[
1104                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1105                        *properties_locs[exp.Properties.Location.POST_WITH],
1106                    ]
1107                )
1108            )
1109
1110            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1111                properties_sql = self.sep() + properties_sql
1112            elif not self.pretty:
1113                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1114                properties_sql = f" {properties_sql}"
1115
1116        begin = " BEGIN" if expression.args.get("begin") else ""
1117        end = " END" if expression.args.get("end") else ""
1118
1119        expression_sql = self.sql(expression, "expression")
1120        if expression_sql:
1121            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1122
1123            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1124                postalias_props_sql = ""
1125                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1126                    postalias_props_sql = self.properties(
1127                        exp.Properties(
1128                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1129                        ),
1130                        wrapped=False,
1131                    )
1132                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1133                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1134
1135        postindex_props_sql = ""
1136        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1137            postindex_props_sql = self.properties(
1138                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1139                wrapped=False,
1140                prefix=" ",
1141            )
1142
1143        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1144        indexes = f" {indexes}" if indexes else ""
1145        index_sql = indexes + postindex_props_sql
1146
1147        replace = " OR REPLACE" if expression.args.get("replace") else ""
1148        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1149        unique = " UNIQUE" if expression.args.get("unique") else ""
1150
1151        clustered = expression.args.get("clustered")
1152        if clustered is None:
1153            clustered_sql = ""
1154        elif clustered:
1155            clustered_sql = " CLUSTERED COLUMNSTORE"
1156        else:
1157            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1158
1159        postcreate_props_sql = ""
1160        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1161            postcreate_props_sql = self.properties(
1162                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1163                sep=" ",
1164                prefix=" ",
1165                wrapped=False,
1166            )
1167
1168        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1169
1170        postexpression_props_sql = ""
1171        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1172            postexpression_props_sql = self.properties(
1173                exp.Properties(
1174                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1175                ),
1176                sep=" ",
1177                prefix=" ",
1178                wrapped=False,
1179            )
1180
1181        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1182        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1183        no_schema_binding = (
1184            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1185        )
1186
1187        clone = self.sql(expression, "clone")
1188        clone = f" {clone}" if clone else ""
1189
1190        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1191            properties_expression = f"{expression_sql}{properties_sql}"
1192        else:
1193            properties_expression = f"{properties_sql}{expression_sql}"
1194
1195        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1196        return self.prepend_ctes(expression, expression_sql)
def sequenceproperties_sql(self, expression: sqlglot.expressions.SequenceProperties) -> str:
1198    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1199        start = self.sql(expression, "start")
1200        start = f"START WITH {start}" if start else ""
1201        increment = self.sql(expression, "increment")
1202        increment = f" INCREMENT BY {increment}" if increment else ""
1203        minvalue = self.sql(expression, "minvalue")
1204        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1205        maxvalue = self.sql(expression, "maxvalue")
1206        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1207        owned = self.sql(expression, "owned")
1208        owned = f" OWNED BY {owned}" if owned else ""
1209
1210        cache = expression.args.get("cache")
1211        if cache is None:
1212            cache_str = ""
1213        elif cache is True:
1214            cache_str = " CACHE"
1215        else:
1216            cache_str = f" CACHE {cache}"
1217
1218        options = self.expressions(expression, key="options", flat=True, sep=" ")
1219        options = f" {options}" if options else ""
1220
1221        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
def clone_sql(self, expression: sqlglot.expressions.Clone) -> str:
1223    def clone_sql(self, expression: exp.Clone) -> str:
1224        this = self.sql(expression, "this")
1225        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1226        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1227        return f"{shallow}{keyword} {this}"
def describe_sql(self, expression: sqlglot.expressions.Describe) -> str:
1229    def describe_sql(self, expression: exp.Describe) -> str:
1230        style = expression.args.get("style")
1231        style = f" {style}" if style else ""
1232        partition = self.sql(expression, "partition")
1233        partition = f" {partition}" if partition else ""
1234        format = self.sql(expression, "format")
1235        format = f" {format}" if format else ""
1236
1237        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
def heredoc_sql(self, expression: sqlglot.expressions.Heredoc) -> str:
1239    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1240        tag = self.sql(expression, "tag")
1241        return f"${tag}${self.sql(expression, 'this')}${tag}$"
def prepend_ctes(self, expression: sqlglot.expressions.Expression, sql: str) -> str:
1243    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1244        with_ = self.sql(expression, "with")
1245        if with_:
1246            sql = f"{with_}{self.sep()}{sql}"
1247        return sql
def with_sql(self, expression: sqlglot.expressions.With) -> str:
1249    def with_sql(self, expression: exp.With) -> str:
1250        sql = self.expressions(expression, flat=True)
1251        recursive = (
1252            "RECURSIVE "
1253            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1254            else ""
1255        )
1256        search = self.sql(expression, "search")
1257        search = f" {search}" if search else ""
1258
1259        return f"WITH {recursive}{sql}{search}"
def cte_sql(self, expression: sqlglot.expressions.CTE) -> str:
1261    def cte_sql(self, expression: exp.CTE) -> str:
1262        alias = expression.args.get("alias")
1263        if alias:
1264            alias.add_comments(expression.pop_comments())
1265
1266        alias_sql = self.sql(expression, "alias")
1267
1268        materialized = expression.args.get("materialized")
1269        if materialized is False:
1270            materialized = "NOT MATERIALIZED "
1271        elif materialized:
1272            materialized = "MATERIALIZED "
1273
1274        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
def tablealias_sql(self, expression: sqlglot.expressions.TableAlias) -> str:
1276    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1277        alias = self.sql(expression, "this")
1278        columns = self.expressions(expression, key="columns", flat=True)
1279        columns = f"({columns})" if columns else ""
1280
1281        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1282            columns = ""
1283            self.unsupported("Named columns are not supported in table alias.")
1284
1285        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1286            alias = self._next_name()
1287
1288        return f"{alias}{columns}"
def bitstring_sql(self, expression: sqlglot.expressions.BitString) -> str:
1290    def bitstring_sql(self, expression: exp.BitString) -> str:
1291        this = self.sql(expression, "this")
1292        if self.dialect.BIT_START:
1293            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1294        return f"{int(this, 2)}"
def hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1296    def hexstring_sql(
1297        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1298    ) -> str:
1299        this = self.sql(expression, "this")
1300        is_integer_type = expression.args.get("is_integer")
1301
1302        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1303            not self.dialect.HEX_START and not binary_function_repr
1304        ):
1305            # Integer representation will be returned if:
1306            # - The read dialect treats the hex value as integer literal but not the write
1307            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1308            return f"{int(this, 16)}"
1309
1310        if not is_integer_type:
1311            # Read dialect treats the hex value as BINARY/BLOB
1312            if binary_function_repr:
1313                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1314                return self.func(binary_function_repr, exp.Literal.string(this))
1315            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1316                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1317                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1318
1319        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
def bytestring_sql(self, expression: sqlglot.expressions.ByteString) -> str:
1321    def bytestring_sql(self, expression: exp.ByteString) -> str:
1322        this = self.sql(expression, "this")
1323        if self.dialect.BYTE_START:
1324            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1325        return this
def unicodestring_sql(self, expression: sqlglot.expressions.UnicodeString) -> str:
1327    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1328        this = self.sql(expression, "this")
1329        escape = expression.args.get("escape")
1330
1331        if self.dialect.UNICODE_START:
1332            escape_substitute = r"\\\1"
1333            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1334        else:
1335            escape_substitute = r"\\u\1"
1336            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1337
1338        if escape:
1339            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1340            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1341        else:
1342            escape_pattern = ESCAPED_UNICODE_RE
1343            escape_sql = ""
1344
1345        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1346            this = escape_pattern.sub(escape_substitute, this)
1347
1348        return f"{left_quote}{this}{right_quote}{escape_sql}"
def rawstring_sql(self, expression: sqlglot.expressions.RawString) -> str:
1350    def rawstring_sql(self, expression: exp.RawString) -> str:
1351        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
1352        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
def datatypeparam_sql(self, expression: sqlglot.expressions.DataTypeParam) -> str:
1354    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1355        this = self.sql(expression, "this")
1356        specifier = self.sql(expression, "expression")
1357        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1358        return f"{this}{specifier}"
def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str:
1360    def datatype_sql(self, expression: exp.DataType) -> str:
1361        nested = ""
1362        values = ""
1363        interior = self.expressions(expression, flat=True)
1364
1365        type_value = expression.this
1366        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1367            type_sql = self.sql(expression, "kind")
1368        else:
1369            type_sql = (
1370                self.TYPE_MAPPING.get(type_value, type_value.value)
1371                if isinstance(type_value, exp.DataType.Type)
1372                else type_value
1373            )
1374
1375        if interior:
1376            if expression.args.get("nested"):
1377                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1378                if expression.args.get("values") is not None:
1379                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1380                    values = self.expressions(expression, key="values", flat=True)
1381                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1382            elif type_value == exp.DataType.Type.INTERVAL:
1383                nested = f" {interior}"
1384            else:
1385                nested = f"({interior})"
1386
1387        type_sql = f"{type_sql}{nested}{values}"
1388        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1389            exp.DataType.Type.TIMETZ,
1390            exp.DataType.Type.TIMESTAMPTZ,
1391        ):
1392            type_sql = f"{type_sql} WITH TIME ZONE"
1393
1394        return type_sql
def directory_sql(self, expression: sqlglot.expressions.Directory) -> str:
1396    def directory_sql(self, expression: exp.Directory) -> str:
1397        local = "LOCAL " if expression.args.get("local") else ""
1398        row_format = self.sql(expression, "row_format")
1399        row_format = f" {row_format}" if row_format else ""
1400        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
def delete_sql(self, expression: sqlglot.expressions.Delete) -> str:
1402    def delete_sql(self, expression: exp.Delete) -> str:
1403        this = self.sql(expression, "this")
1404        this = f" FROM {this}" if this else ""
1405        using = self.sql(expression, "using")
1406        using = f" USING {using}" if using else ""
1407        cluster = self.sql(expression, "cluster")
1408        cluster = f" {cluster}" if cluster else ""
1409        where = self.sql(expression, "where")
1410        returning = self.sql(expression, "returning")
1411        limit = self.sql(expression, "limit")
1412        tables = self.expressions(expression, key="tables")
1413        tables = f" {tables}" if tables else ""
1414        if self.RETURNING_END:
1415            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1416        else:
1417            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1418        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
def drop_sql(self, expression: sqlglot.expressions.Drop) -> str:
1420    def drop_sql(self, expression: exp.Drop) -> str:
1421        this = self.sql(expression, "this")
1422        expressions = self.expressions(expression, flat=True)
1423        expressions = f" ({expressions})" if expressions else ""
1424        kind = expression.args["kind"]
1425        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1426        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1427        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1428        on_cluster = self.sql(expression, "cluster")
1429        on_cluster = f" {on_cluster}" if on_cluster else ""
1430        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1431        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1432        cascade = " CASCADE" if expression.args.get("cascade") else ""
1433        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1434        purge = " PURGE" if expression.args.get("purge") else ""
1435        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
def set_operation(self, expression: sqlglot.expressions.SetOperation) -> str:
1437    def set_operation(self, expression: exp.SetOperation) -> str:
1438        op_type = type(expression)
1439        op_name = op_type.key.upper()
1440
1441        distinct = expression.args.get("distinct")
1442        if (
1443            distinct is False
1444            and op_type in (exp.Except, exp.Intersect)
1445            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1446        ):
1447            self.unsupported(f"{op_name} ALL is not supported")
1448
1449        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1450
1451        if distinct is None:
1452            distinct = default_distinct
1453            if distinct is None:
1454                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1455
1456        if distinct is default_distinct:
1457            distinct_or_all = ""
1458        else:
1459            distinct_or_all = " DISTINCT" if distinct else " ALL"
1460
1461        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1462        side_kind = f"{side_kind} " if side_kind else ""
1463
1464        by_name = " BY NAME" if expression.args.get("by_name") else ""
1465        on = self.expressions(expression, key="on", flat=True)
1466        on = f" ON ({on})" if on else ""
1467
1468        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
def set_operations(self, expression: sqlglot.expressions.SetOperation) -> str:
1470    def set_operations(self, expression: exp.SetOperation) -> str:
1471        if not self.SET_OP_MODIFIERS:
1472            limit = expression.args.get("limit")
1473            order = expression.args.get("order")
1474
1475            if limit or order:
1476                select = self._move_ctes_to_top_level(
1477                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1478                )
1479
1480                if limit:
1481                    select = select.limit(limit.pop(), copy=False)
1482                if order:
1483                    select = select.order_by(order.pop(), copy=False)
1484                return self.sql(select)
1485
1486        sqls: t.List[str] = []
1487        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1488
1489        while stack:
1490            node = stack.pop()
1491
1492            if isinstance(node, exp.SetOperation):
1493                stack.append(node.expression)
1494                stack.append(
1495                    self.maybe_comment(
1496                        self.set_operation(node), comments=node.comments, separated=True
1497                    )
1498                )
1499                stack.append(node.this)
1500            else:
1501                sqls.append(self.sql(node))
1502
1503        this = self.sep().join(sqls)
1504        this = self.query_modifiers(expression, this)
1505        return self.prepend_ctes(expression, this)
def fetch_sql(self, expression: sqlglot.expressions.Fetch) -> str:
1507    def fetch_sql(self, expression: exp.Fetch) -> str:
1508        direction = expression.args.get("direction")
1509        direction = f" {direction}" if direction else ""
1510        count = self.sql(expression, "count")
1511        count = f" {count}" if count else ""
1512        limit_options = self.sql(expression, "limit_options")
1513        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1514        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
def limitoptions_sql(self, expression: sqlglot.expressions.LimitOptions) -> str:
1516    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1517        percent = " PERCENT" if expression.args.get("percent") else ""
1518        rows = " ROWS" if expression.args.get("rows") else ""
1519        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1520        if not with_ties and rows:
1521            with_ties = " ONLY"
1522        return f"{percent}{rows}{with_ties}"
def filter_sql(self, expression: sqlglot.expressions.Filter) -> str:
1524    def filter_sql(self, expression: exp.Filter) -> str:
1525        if self.AGGREGATE_FILTER_SUPPORTED:
1526            this = self.sql(expression, "this")
1527            where = self.sql(expression, "expression").strip()
1528            return f"{this} FILTER({where})"
1529
1530        agg = expression.this
1531        agg_arg = agg.this
1532        cond = expression.expression.this
1533        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1534        return self.sql(agg)
def hint_sql(self, expression: sqlglot.expressions.Hint) -> str:
1536    def hint_sql(self, expression: exp.Hint) -> str:
1537        if not self.QUERY_HINTS:
1538            self.unsupported("Hints are not supported")
1539            return ""
1540
1541        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
def indexparameters_sql(self, expression: sqlglot.expressions.IndexParameters) -> str:
1543    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1544        using = self.sql(expression, "using")
1545        using = f" USING {using}" if using else ""
1546        columns = self.expressions(expression, key="columns", flat=True)
1547        columns = f"({columns})" if columns else ""
1548        partition_by = self.expressions(expression, key="partition_by", flat=True)
1549        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1550        where = self.sql(expression, "where")
1551        include = self.expressions(expression, key="include", flat=True)
1552        if include:
1553            include = f" INCLUDE ({include})"
1554        with_storage = self.expressions(expression, key="with_storage", flat=True)
1555        with_storage = f" WITH ({with_storage})" if with_storage else ""
1556        tablespace = self.sql(expression, "tablespace")
1557        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1558        on = self.sql(expression, "on")
1559        on = f" ON {on}" if on else ""
1560
1561        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
def index_sql(self, expression: sqlglot.expressions.Index) -> str:
1563    def index_sql(self, expression: exp.Index) -> str:
1564        unique = "UNIQUE " if expression.args.get("unique") else ""
1565        primary = "PRIMARY " if expression.args.get("primary") else ""
1566        amp = "AMP " if expression.args.get("amp") else ""
1567        name = self.sql(expression, "this")
1568        name = f"{name} " if name else ""
1569        table = self.sql(expression, "table")
1570        table = f"{self.INDEX_ON} {table}" if table else ""
1571
1572        index = "INDEX " if not table else ""
1573
1574        params = self.sql(expression, "params")
1575        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
1577    def identifier_sql(self, expression: exp.Identifier) -> str:
1578        text = expression.name
1579        lower = text.lower()
1580        text = lower if self.normalize and not expression.quoted else text
1581        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1582        if (
1583            expression.quoted
1584            or self.dialect.can_identify(text, self.identify)
1585            or lower in self.RESERVED_KEYWORDS
1586            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1587        ):
1588            text = f"{self._identifier_start}{text}{self._identifier_end}"
1589        return text
def hex_sql(self, expression: sqlglot.expressions.Hex) -> str:
1591    def hex_sql(self, expression: exp.Hex) -> str:
1592        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1593        if self.dialect.HEX_LOWERCASE:
1594            text = self.func("LOWER", text)
1595
1596        return text
def lowerhex_sql(self, expression: sqlglot.expressions.LowerHex) -> str:
1598    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1599        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1600        if not self.dialect.HEX_LOWERCASE:
1601            text = self.func("LOWER", text)
1602        return text
def inputoutputformat_sql(self, expression: sqlglot.expressions.InputOutputFormat) -> str:
1604    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1605        input_format = self.sql(expression, "input_format")
1606        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1607        output_format = self.sql(expression, "output_format")
1608        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1609        return self.sep().join((input_format, output_format))
def national_sql(self, expression: sqlglot.expressions.National, prefix: str = 'N') -> str:
1611    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1612        string = self.sql(exp.Literal.string(expression.name))
1613        return f"{prefix}{string}"
def partition_sql(self, expression: sqlglot.expressions.Partition) -> str:
1615    def partition_sql(self, expression: exp.Partition) -> str:
1616        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1617        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
def properties_sql(self, expression: sqlglot.expressions.Properties) -> str:
1619    def properties_sql(self, expression: exp.Properties) -> str:
1620        root_properties = []
1621        with_properties = []
1622
1623        for p in expression.expressions:
1624            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1625            if p_loc == exp.Properties.Location.POST_WITH:
1626                with_properties.append(p)
1627            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1628                root_properties.append(p)
1629
1630        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1631        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1632
1633        if root_props and with_props and not self.pretty:
1634            with_props = " " + with_props
1635
1636        return root_props + with_props
def root_properties(self, properties: sqlglot.expressions.Properties) -> str:
1638    def root_properties(self, properties: exp.Properties) -> str:
1639        if properties.expressions:
1640            return self.expressions(properties, indent=False, sep=" ")
1641        return ""
def properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1643    def properties(
1644        self,
1645        properties: exp.Properties,
1646        prefix: str = "",
1647        sep: str = ", ",
1648        suffix: str = "",
1649        wrapped: bool = True,
1650    ) -> str:
1651        if properties.expressions:
1652            expressions = self.expressions(properties, sep=sep, indent=False)
1653            if expressions:
1654                expressions = self.wrap(expressions) if wrapped else expressions
1655                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1656        return ""
def with_properties(self, properties: sqlglot.expressions.Properties) -> str:
1658    def with_properties(self, properties: exp.Properties) -> str:
1659        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
def locate_properties(self, properties: sqlglot.expressions.Properties) -> DefaultDict:
1661    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1662        properties_locs = defaultdict(list)
1663        for p in properties.expressions:
1664            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1665            if p_loc != exp.Properties.Location.UNSUPPORTED:
1666                properties_locs[p_loc].append(p)
1667            else:
1668                self.unsupported(f"Unsupported property {p.key}")
1669
1670        return properties_locs
def property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1672    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1673        if isinstance(expression.this, exp.Dot):
1674            return self.sql(expression, "this")
1675        return f"'{expression.name}'" if string_key else expression.name
def property_sql(self, expression: sqlglot.expressions.Property) -> str:
1677    def property_sql(self, expression: exp.Property) -> str:
1678        property_cls = expression.__class__
1679        if property_cls == exp.Property:
1680            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1681
1682        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1683        if not property_name:
1684            self.unsupported(f"Unsupported property {expression.key}")
1685
1686        return f"{property_name}={self.sql(expression, 'this')}"
def likeproperty_sql(self, expression: sqlglot.expressions.LikeProperty) -> str:
1688    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1689        if self.SUPPORTS_CREATE_TABLE_LIKE:
1690            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1691            options = f" {options}" if options else ""
1692
1693            like = f"LIKE {self.sql(expression, 'this')}{options}"
1694            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1695                like = f"({like})"
1696
1697            return like
1698
1699        if expression.expressions:
1700            self.unsupported("Transpilation of LIKE property options is unsupported")
1701
1702        select = exp.select("*").from_(expression.this).limit(0)
1703        return f"AS {self.sql(select)}"
def fallbackproperty_sql(self, expression: sqlglot.expressions.FallbackProperty) -> str:
1705    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1706        no = "NO " if expression.args.get("no") else ""
1707        protection = " PROTECTION" if expression.args.get("protection") else ""
1708        return f"{no}FALLBACK{protection}"
def journalproperty_sql(self, expression: sqlglot.expressions.JournalProperty) -> str:
1710    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1711        no = "NO " if expression.args.get("no") else ""
1712        local = expression.args.get("local")
1713        local = f"{local} " if local else ""
1714        dual = "DUAL " if expression.args.get("dual") else ""
1715        before = "BEFORE " if expression.args.get("before") else ""
1716        after = "AFTER " if expression.args.get("after") else ""
1717        return f"{no}{local}{dual}{before}{after}JOURNAL"
def freespaceproperty_sql(self, expression: sqlglot.expressions.FreespaceProperty) -> str:
1719    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1720        freespace = self.sql(expression, "this")
1721        percent = " PERCENT" if expression.args.get("percent") else ""
1722        return f"FREESPACE={freespace}{percent}"
def checksumproperty_sql(self, expression: sqlglot.expressions.ChecksumProperty) -> str:
1724    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1725        if expression.args.get("default"):
1726            property = "DEFAULT"
1727        elif expression.args.get("on"):
1728            property = "ON"
1729        else:
1730            property = "OFF"
1731        return f"CHECKSUM={property}"
def mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1733    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1734        if expression.args.get("no"):
1735            return "NO MERGEBLOCKRATIO"
1736        if expression.args.get("default"):
1737            return "DEFAULT MERGEBLOCKRATIO"
1738
1739        percent = " PERCENT" if expression.args.get("percent") else ""
1740        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
def datablocksizeproperty_sql(self, expression: sqlglot.expressions.DataBlocksizeProperty) -> str:
1742    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1743        default = expression.args.get("default")
1744        minimum = expression.args.get("minimum")
1745        maximum = expression.args.get("maximum")
1746        if default or minimum or maximum:
1747            if default:
1748                prop = "DEFAULT"
1749            elif minimum:
1750                prop = "MINIMUM"
1751            else:
1752                prop = "MAXIMUM"
1753            return f"{prop} DATABLOCKSIZE"
1754        units = expression.args.get("units")
1755        units = f" {units}" if units else ""
1756        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1758    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1759        autotemp = expression.args.get("autotemp")
1760        always = expression.args.get("always")
1761        default = expression.args.get("default")
1762        manual = expression.args.get("manual")
1763        never = expression.args.get("never")
1764
1765        if autotemp is not None:
1766            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1767        elif always:
1768            prop = "ALWAYS"
1769        elif default:
1770            prop = "DEFAULT"
1771        elif manual:
1772            prop = "MANUAL"
1773        elif never:
1774            prop = "NEVER"
1775        return f"BLOCKCOMPRESSION={prop}"
def isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1777    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1778        no = expression.args.get("no")
1779        no = " NO" if no else ""
1780        concurrent = expression.args.get("concurrent")
1781        concurrent = " CONCURRENT" if concurrent else ""
1782        target = self.sql(expression, "target")
1783        target = f" {target}" if target else ""
1784        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
def partitionboundspec_sql(self, expression: sqlglot.expressions.PartitionBoundSpec) -> str:
1786    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1787        if isinstance(expression.this, list):
1788            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1789        if expression.this:
1790            modulus = self.sql(expression, "this")
1791            remainder = self.sql(expression, "expression")
1792            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1793
1794        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1795        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1796        return f"FROM ({from_expressions}) TO ({to_expressions})"
def partitionedofproperty_sql(self, expression: sqlglot.expressions.PartitionedOfProperty) -> str:
1798    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1799        this = self.sql(expression, "this")
1800
1801        for_values_or_default = expression.expression
1802        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1803            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1804        else:
1805            for_values_or_default = " DEFAULT"
1806
1807        return f"PARTITION OF {this}{for_values_or_default}"
def lockingproperty_sql(self, expression: sqlglot.expressions.LockingProperty) -> str:
1809    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1810        kind = expression.args.get("kind")
1811        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1812        for_or_in = expression.args.get("for_or_in")
1813        for_or_in = f" {for_or_in}" if for_or_in else ""
1814        lock_type = expression.args.get("lock_type")
1815        override = " OVERRIDE" if expression.args.get("override") else ""
1816        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
def withdataproperty_sql(self, expression: sqlglot.expressions.WithDataProperty) -> str:
1818    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1819        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1820        statistics = expression.args.get("statistics")
1821        statistics_sql = ""
1822        if statistics is not None:
1823            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1824        return f"{data_sql}{statistics_sql}"
def withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1826    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1827        this = self.sql(expression, "this")
1828        this = f"HISTORY_TABLE={this}" if this else ""
1829        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1830        data_consistency = (
1831            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1832        )
1833        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1834        retention_period = (
1835            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1836        )
1837
1838        if this:
1839            on_sql = self.func("ON", this, data_consistency, retention_period)
1840        else:
1841            on_sql = "ON" if expression.args.get("on") else "OFF"
1842
1843        sql = f"SYSTEM_VERSIONING={on_sql}"
1844
1845        return f"WITH({sql})" if expression.args.get("with") else sql
def insert_sql(self, expression: sqlglot.expressions.Insert) -> str:
1847    def insert_sql(self, expression: exp.Insert) -> str:
1848        hint = self.sql(expression, "hint")
1849        overwrite = expression.args.get("overwrite")
1850
1851        if isinstance(expression.this, exp.Directory):
1852            this = " OVERWRITE" if overwrite else " INTO"
1853        else:
1854            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1855
1856        stored = self.sql(expression, "stored")
1857        stored = f" {stored}" if stored else ""
1858        alternative = expression.args.get("alternative")
1859        alternative = f" OR {alternative}" if alternative else ""
1860        ignore = " IGNORE" if expression.args.get("ignore") else ""
1861        is_function = expression.args.get("is_function")
1862        if is_function:
1863            this = f"{this} FUNCTION"
1864        this = f"{this} {self.sql(expression, 'this')}"
1865
1866        exists = " IF EXISTS" if expression.args.get("exists") else ""
1867        where = self.sql(expression, "where")
1868        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1869        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1870        on_conflict = self.sql(expression, "conflict")
1871        on_conflict = f" {on_conflict}" if on_conflict else ""
1872        by_name = " BY NAME" if expression.args.get("by_name") else ""
1873        returning = self.sql(expression, "returning")
1874
1875        if self.RETURNING_END:
1876            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1877        else:
1878            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1879
1880        partition_by = self.sql(expression, "partition")
1881        partition_by = f" {partition_by}" if partition_by else ""
1882        settings = self.sql(expression, "settings")
1883        settings = f" {settings}" if settings else ""
1884
1885        source = self.sql(expression, "source")
1886        source = f"TABLE {source}" if source else ""
1887
1888        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1889        return self.prepend_ctes(expression, sql)
def introducer_sql(self, expression: sqlglot.expressions.Introducer) -> str:
1891    def introducer_sql(self, expression: exp.Introducer) -> str:
1892        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def kill_sql(self, expression: sqlglot.expressions.Kill) -> str:
1894    def kill_sql(self, expression: exp.Kill) -> str:
1895        kind = self.sql(expression, "kind")
1896        kind = f" {kind}" if kind else ""
1897        this = self.sql(expression, "this")
1898        this = f" {this}" if this else ""
1899        return f"KILL{kind}{this}"
def pseudotype_sql(self, expression: sqlglot.expressions.PseudoType) -> str:
1901    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1902        return expression.name
def objectidentifier_sql(self, expression: sqlglot.expressions.ObjectIdentifier) -> str:
1904    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1905        return expression.name
def onconflict_sql(self, expression: sqlglot.expressions.OnConflict) -> str:
1907    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1908        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1909
1910        constraint = self.sql(expression, "constraint")
1911        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1912
1913        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1914        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1915        action = self.sql(expression, "action")
1916
1917        expressions = self.expressions(expression, flat=True)
1918        if expressions:
1919            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1920            expressions = f" {set_keyword}{expressions}"
1921
1922        where = self.sql(expression, "where")
1923        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
1925    def returning_sql(self, expression: exp.Returning) -> str:
1926        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
def rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1928    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1929        fields = self.sql(expression, "fields")
1930        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1931        escaped = self.sql(expression, "escaped")
1932        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1933        items = self.sql(expression, "collection_items")
1934        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1935        keys = self.sql(expression, "map_keys")
1936        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1937        lines = self.sql(expression, "lines")
1938        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1939        null = self.sql(expression, "null")
1940        null = f" NULL DEFINED AS {null}" if null else ""
1941        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
def withtablehint_sql(self, expression: sqlglot.expressions.WithTableHint) -> str:
1943    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1944        return f"WITH ({self.expressions(expression, flat=True)})"
def indextablehint_sql(self, expression: sqlglot.expressions.IndexTableHint) -> str:
1946    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1947        this = f"{self.sql(expression, 'this')} INDEX"
1948        target = self.sql(expression, "target")
1949        target = f" FOR {target}" if target else ""
1950        return f"{this}{target} ({self.expressions(expression, flat=True)})"
def historicaldata_sql(self, expression: sqlglot.expressions.HistoricalData) -> str:
1952    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1953        this = self.sql(expression, "this")
1954        kind = self.sql(expression, "kind")
1955        expr = self.sql(expression, "expression")
1956        return f"{this} ({kind} => {expr})"
def table_parts(self, expression: sqlglot.expressions.Table) -> str:
1958    def table_parts(self, expression: exp.Table) -> str:
1959        return ".".join(
1960            self.sql(part)
1961            for part in (
1962                expression.args.get("catalog"),
1963                expression.args.get("db"),
1964                expression.args.get("this"),
1965            )
1966            if part is not None
1967        )
def table_sql(self, expression: sqlglot.expressions.Table, sep: str = ' AS ') -> str:
1969    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1970        table = self.table_parts(expression)
1971        only = "ONLY " if expression.args.get("only") else ""
1972        partition = self.sql(expression, "partition")
1973        partition = f" {partition}" if partition else ""
1974        version = self.sql(expression, "version")
1975        version = f" {version}" if version else ""
1976        alias = self.sql(expression, "alias")
1977        alias = f"{sep}{alias}" if alias else ""
1978
1979        sample = self.sql(expression, "sample")
1980        if self.dialect.ALIAS_POST_TABLESAMPLE:
1981            sample_pre_alias = sample
1982            sample_post_alias = ""
1983        else:
1984            sample_pre_alias = ""
1985            sample_post_alias = sample
1986
1987        hints = self.expressions(expression, key="hints", sep=" ")
1988        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
1989        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
1990        joins = self.indent(
1991            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
1992        )
1993        laterals = self.expressions(expression, key="laterals", sep="")
1994
1995        file_format = self.sql(expression, "format")
1996        if file_format:
1997            pattern = self.sql(expression, "pattern")
1998            pattern = f", PATTERN => {pattern}" if pattern else ""
1999            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
2000
2001        ordinality = expression.args.get("ordinality") or ""
2002        if ordinality:
2003            ordinality = f" WITH ORDINALITY{alias}"
2004            alias = ""
2005
2006        when = self.sql(expression, "when")
2007        if when:
2008            table = f"{table} {when}"
2009
2010        changes = self.sql(expression, "changes")
2011        changes = f" {changes}" if changes else ""
2012
2013        rows_from = self.expressions(expression, key="rows_from")
2014        if rows_from:
2015            table = f"ROWS FROM {self.wrap(rows_from)}"
2016
2017        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def tablefromrows_sql(self, expression: sqlglot.expressions.TableFromRows) -> str:
2019    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2020        table = self.func("TABLE", expression.this)
2021        alias = self.sql(expression, "alias")
2022        alias = f" AS {alias}" if alias else ""
2023        sample = self.sql(expression, "sample")
2024        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2025        joins = self.indent(
2026            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2027        )
2028        return f"{table}{alias}{pivots}{sample}{joins}"
def tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2030    def tablesample_sql(
2031        self,
2032        expression: exp.TableSample,
2033        tablesample_keyword: t.Optional[str] = None,
2034    ) -> str:
2035        method = self.sql(expression, "method")
2036        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2037        numerator = self.sql(expression, "bucket_numerator")
2038        denominator = self.sql(expression, "bucket_denominator")
2039        field = self.sql(expression, "bucket_field")
2040        field = f" ON {field}" if field else ""
2041        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2042        seed = self.sql(expression, "seed")
2043        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2044
2045        size = self.sql(expression, "size")
2046        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2047            size = f"{size} ROWS"
2048
2049        percent = self.sql(expression, "percent")
2050        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2051            percent = f"{percent} PERCENT"
2052
2053        expr = f"{bucket}{percent}{size}"
2054        if self.TABLESAMPLE_REQUIRES_PARENS:
2055            expr = f"({expr})"
2056
2057        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
def pivot_sql(self, expression: sqlglot.expressions.Pivot) -> str:
2059    def pivot_sql(self, expression: exp.Pivot) -> str:
2060        expressions = self.expressions(expression, flat=True)
2061        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2062
2063        group = self.sql(expression, "group")
2064
2065        if expression.this:
2066            this = self.sql(expression, "this")
2067            if not expressions:
2068                return f"UNPIVOT {this}"
2069
2070            on = f"{self.seg('ON')} {expressions}"
2071            into = self.sql(expression, "into")
2072            into = f"{self.seg('INTO')} {into}" if into else ""
2073            using = self.expressions(expression, key="using", flat=True)
2074            using = f"{self.seg('USING')} {using}" if using else ""
2075            return f"{direction} {this}{on}{into}{using}{group}"
2076
2077        alias = self.sql(expression, "alias")
2078        alias = f" AS {alias}" if alias else ""
2079
2080        fields = self.expressions(
2081            expression,
2082            "fields",
2083            sep=" ",
2084            dynamic=True,
2085            new_line=True,
2086            skip_first=True,
2087            skip_last=True,
2088        )
2089
2090        include_nulls = expression.args.get("include_nulls")
2091        if include_nulls is not None:
2092            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2093        else:
2094            nulls = ""
2095
2096        default_on_null = self.sql(expression, "default_on_null")
2097        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2098        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
2100    def version_sql(self, expression: exp.Version) -> str:
2101        this = f"FOR {expression.name}"
2102        kind = expression.text("kind")
2103        expr = self.sql(expression, "expression")
2104        return f"{this} {kind} {expr}"
def tuple_sql(self, expression: sqlglot.expressions.Tuple) -> str:
2106    def tuple_sql(self, expression: exp.Tuple) -> str:
2107        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
def update_sql(self, expression: sqlglot.expressions.Update) -> str:
2109    def update_sql(self, expression: exp.Update) -> str:
2110        this = self.sql(expression, "this")
2111        set_sql = self.expressions(expression, flat=True)
2112        from_sql = self.sql(expression, "from")
2113        where_sql = self.sql(expression, "where")
2114        returning = self.sql(expression, "returning")
2115        order = self.sql(expression, "order")
2116        limit = self.sql(expression, "limit")
2117        if self.RETURNING_END:
2118            expression_sql = f"{from_sql}{where_sql}{returning}"
2119        else:
2120            expression_sql = f"{returning}{from_sql}{where_sql}"
2121        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2122        return self.prepend_ctes(expression, sql)
def values_sql( self, expression: sqlglot.expressions.Values, values_as_table: bool = True) -> str:
2124    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2125        values_as_table = values_as_table and self.VALUES_AS_TABLE
2126
2127        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2128        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2129            args = self.expressions(expression)
2130            alias = self.sql(expression, "alias")
2131            values = f"VALUES{self.seg('')}{args}"
2132            values = (
2133                f"({values})"
2134                if self.WRAP_DERIVED_VALUES
2135                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2136                else values
2137            )
2138            return f"{values} AS {alias}" if alias else values
2139
2140        # Converts `VALUES...` expression into a series of select unions.
2141        alias_node = expression.args.get("alias")
2142        column_names = alias_node and alias_node.columns
2143
2144        selects: t.List[exp.Query] = []
2145
2146        for i, tup in enumerate(expression.expressions):
2147            row = tup.expressions
2148
2149            if i == 0 and column_names:
2150                row = [
2151                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2152                ]
2153
2154            selects.append(exp.Select(expressions=row))
2155
2156        if self.pretty:
2157            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2158            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2159            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2160            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2161            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2162
2163        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2164        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2165        return f"({unions}){alias}"
def var_sql(self, expression: sqlglot.expressions.Var) -> str:
2167    def var_sql(self, expression: exp.Var) -> str:
2168        return self.sql(expression, "this")
@unsupported_args('expressions')
def into_sql(self, expression: sqlglot.expressions.Into) -> str:
2170    @unsupported_args("expressions")
2171    def into_sql(self, expression: exp.Into) -> str:
2172        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2173        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2174        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
def from_sql(self, expression: sqlglot.expressions.From) -> str:
2176    def from_sql(self, expression: exp.From) -> str:
2177        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
def groupingsets_sql(self, expression: sqlglot.expressions.GroupingSets) -> str:
2179    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2180        grouping_sets = self.expressions(expression, indent=False)
2181        return f"GROUPING SETS {self.wrap(grouping_sets)}"
def rollup_sql(self, expression: sqlglot.expressions.Rollup) -> str:
2183    def rollup_sql(self, expression: exp.Rollup) -> str:
2184        expressions = self.expressions(expression, indent=False)
2185        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
def cube_sql(self, expression: sqlglot.expressions.Cube) -> str:
2187    def cube_sql(self, expression: exp.Cube) -> str:
2188        expressions = self.expressions(expression, indent=False)
2189        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
def group_sql(self, expression: sqlglot.expressions.Group) -> str:
2191    def group_sql(self, expression: exp.Group) -> str:
2192        group_by_all = expression.args.get("all")
2193        if group_by_all is True:
2194            modifier = " ALL"
2195        elif group_by_all is False:
2196            modifier = " DISTINCT"
2197        else:
2198            modifier = ""
2199
2200        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2201
2202        grouping_sets = self.expressions(expression, key="grouping_sets")
2203        cube = self.expressions(expression, key="cube")
2204        rollup = self.expressions(expression, key="rollup")
2205
2206        groupings = csv(
2207            self.seg(grouping_sets) if grouping_sets else "",
2208            self.seg(cube) if cube else "",
2209            self.seg(rollup) if rollup else "",
2210            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2211            sep=self.GROUPINGS_SEP,
2212        )
2213
2214        if (
2215            expression.expressions
2216            and groupings
2217            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2218        ):
2219            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2220
2221        return f"{group_by}{groupings}"
def having_sql(self, expression: sqlglot.expressions.Having) -> str:
2223    def having_sql(self, expression: exp.Having) -> str:
2224        this = self.indent(self.sql(expression, "this"))
2225        return f"{self.seg('HAVING')}{self.sep()}{this}"
def connect_sql(self, expression: sqlglot.expressions.Connect) -> str:
2227    def connect_sql(self, expression: exp.Connect) -> str:
2228        start = self.sql(expression, "start")
2229        start = self.seg(f"START WITH {start}") if start else ""
2230        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2231        connect = self.sql(expression, "connect")
2232        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2233        return start + connect
def prior_sql(self, expression: sqlglot.expressions.Prior) -> str:
2235    def prior_sql(self, expression: exp.Prior) -> str:
2236        return f"PRIOR {self.sql(expression, 'this')}"
def join_sql(self, expression: sqlglot.expressions.Join) -> str:
2238    def join_sql(self, expression: exp.Join) -> str:
2239        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2240            side = None
2241        else:
2242            side = expression.side
2243
2244        op_sql = " ".join(
2245            op
2246            for op in (
2247                expression.method,
2248                "GLOBAL" if expression.args.get("global") else None,
2249                side,
2250                expression.kind,
2251                expression.hint if self.JOIN_HINTS else None,
2252            )
2253            if op
2254        )
2255        match_cond = self.sql(expression, "match_condition")
2256        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2257        on_sql = self.sql(expression, "on")
2258        using = expression.args.get("using")
2259
2260        if not on_sql and using:
2261            on_sql = csv(*(self.sql(column) for column in using))
2262
2263        this = expression.this
2264        this_sql = self.sql(this)
2265
2266        exprs = self.expressions(expression)
2267        if exprs:
2268            this_sql = f"{this_sql},{self.seg(exprs)}"
2269
2270        if on_sql:
2271            on_sql = self.indent(on_sql, skip_first=True)
2272            space = self.seg(" " * self.pad) if self.pretty else " "
2273            if using:
2274                on_sql = f"{space}USING ({on_sql})"
2275            else:
2276                on_sql = f"{space}ON {on_sql}"
2277        elif not op_sql:
2278            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2279                return f" {this_sql}"
2280
2281            return f", {this_sql}"
2282
2283        if op_sql != "STRAIGHT_JOIN":
2284            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2285
2286        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str:
2288    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2289        args = self.expressions(expression, flat=True)
2290        args = f"({args})" if len(args.split(",")) > 1 else args
2291        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
def lateral_op(self, expression: sqlglot.expressions.Lateral) -> str:
2293    def lateral_op(self, expression: exp.Lateral) -> str:
2294        cross_apply = expression.args.get("cross_apply")
2295
2296        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2297        if cross_apply is True:
2298            op = "INNER JOIN "
2299        elif cross_apply is False:
2300            op = "LEFT JOIN "
2301        else:
2302            op = ""
2303
2304        return f"{op}LATERAL"
def lateral_sql(self, expression: sqlglot.expressions.Lateral) -> str:
2306    def lateral_sql(self, expression: exp.Lateral) -> str:
2307        this = self.sql(expression, "this")
2308
2309        if expression.args.get("view"):
2310            alias = expression.args["alias"]
2311            columns = self.expressions(alias, key="columns", flat=True)
2312            table = f" {alias.name}" if alias.name else ""
2313            columns = f" AS {columns}" if columns else ""
2314            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2315            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2316
2317        alias = self.sql(expression, "alias")
2318        alias = f" AS {alias}" if alias else ""
2319
2320        ordinality = expression.args.get("ordinality") or ""
2321        if ordinality:
2322            ordinality = f" WITH ORDINALITY{alias}"
2323            alias = ""
2324
2325        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
def limit_sql(self, expression: sqlglot.expressions.Limit, top: bool = False) -> str:
2327    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2328        this = self.sql(expression, "this")
2329
2330        args = [
2331            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2332            for e in (expression.args.get(k) for k in ("offset", "expression"))
2333            if e
2334        ]
2335
2336        args_sql = ", ".join(self.sql(e) for e in args)
2337        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2338        expressions = self.expressions(expression, flat=True)
2339        limit_options = self.sql(expression, "limit_options")
2340        expressions = f" BY {expressions}" if expressions else ""
2341
2342        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
2344    def offset_sql(self, expression: exp.Offset) -> str:
2345        this = self.sql(expression, "this")
2346        value = expression.expression
2347        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2348        expressions = self.expressions(expression, flat=True)
2349        expressions = f" BY {expressions}" if expressions else ""
2350        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
2352    def setitem_sql(self, expression: exp.SetItem) -> str:
2353        kind = self.sql(expression, "kind")
2354        kind = f"{kind} " if kind else ""
2355        this = self.sql(expression, "this")
2356        expressions = self.expressions(expression)
2357        collate = self.sql(expression, "collate")
2358        collate = f" COLLATE {collate}" if collate else ""
2359        global_ = "GLOBAL " if expression.args.get("global") else ""
2360        return f"{global_}{kind}{this}{expressions}{collate}"
def set_sql(self, expression: sqlglot.expressions.Set) -> str:
2362    def set_sql(self, expression: exp.Set) -> str:
2363        expressions = f" {self.expressions(expression, flat=True)}"
2364        tag = " TAG" if expression.args.get("tag") else ""
2365        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
def pragma_sql(self, expression: sqlglot.expressions.Pragma) -> str:
2367    def pragma_sql(self, expression: exp.Pragma) -> str:
2368        return f"PRAGMA {self.sql(expression, 'this')}"
def lock_sql(self, expression: sqlglot.expressions.Lock) -> str:
2370    def lock_sql(self, expression: exp.Lock) -> str:
2371        if not self.LOCKING_READS_SUPPORTED:
2372            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2373            return ""
2374
2375        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2376        expressions = self.expressions(expression, flat=True)
2377        expressions = f" OF {expressions}" if expressions else ""
2378        wait = expression.args.get("wait")
2379
2380        if wait is not None:
2381            if isinstance(wait, exp.Literal):
2382                wait = f" WAIT {self.sql(wait)}"
2383            else:
2384                wait = " NOWAIT" if wait else " SKIP LOCKED"
2385
2386        return f"{lock_type}{expressions}{wait or ''}"
def literal_sql(self, expression: sqlglot.expressions.Literal) -> str:
2388    def literal_sql(self, expression: exp.Literal) -> str:
2389        text = expression.this or ""
2390        if expression.is_string:
2391            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2392        return text
def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2394    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2395        if self.dialect.ESCAPED_SEQUENCES:
2396            to_escaped = self.dialect.ESCAPED_SEQUENCES
2397            text = "".join(
2398                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2399            )
2400
2401        return self._replace_line_breaks(text).replace(
2402            self.dialect.QUOTE_END, self._escaped_quote_end
2403        )
def loaddata_sql(self, expression: sqlglot.expressions.LoadData) -> str:
2405    def loaddata_sql(self, expression: exp.LoadData) -> str:
2406        local = " LOCAL" if expression.args.get("local") else ""
2407        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2408        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2409        this = f" INTO TABLE {self.sql(expression, 'this')}"
2410        partition = self.sql(expression, "partition")
2411        partition = f" {partition}" if partition else ""
2412        input_format = self.sql(expression, "input_format")
2413        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2414        serde = self.sql(expression, "serde")
2415        serde = f" SERDE {serde}" if serde else ""
2416        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
def null_sql(self, *_) -> str:
2418    def null_sql(self, *_) -> str:
2419        return "NULL"
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
2421    def boolean_sql(self, expression: exp.Boolean) -> str:
2422        return "TRUE" if expression.this else "FALSE"
def order_sql(self, expression: sqlglot.expressions.Order, flat: bool = False) -> str:
2424    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2425        this = self.sql(expression, "this")
2426        this = f"{this} " if this else this
2427        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2428        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
def withfill_sql(self, expression: sqlglot.expressions.WithFill) -> str:
2430    def withfill_sql(self, expression: exp.WithFill) -> str:
2431        from_sql = self.sql(expression, "from")
2432        from_sql = f" FROM {from_sql}" if from_sql else ""
2433        to_sql = self.sql(expression, "to")
2434        to_sql = f" TO {to_sql}" if to_sql else ""
2435        step_sql = self.sql(expression, "step")
2436        step_sql = f" STEP {step_sql}" if step_sql else ""
2437        interpolated_values = [
2438            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2439            if isinstance(e, exp.Alias)
2440            else self.sql(e, "this")
2441            for e in expression.args.get("interpolate") or []
2442        ]
2443        interpolate = (
2444            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2445        )
2446        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
def cluster_sql(self, expression: sqlglot.expressions.Cluster) -> str:
2448    def cluster_sql(self, expression: exp.Cluster) -> str:
2449        return self.op_expressions("CLUSTER BY", expression)
def distribute_sql(self, expression: sqlglot.expressions.Distribute) -> str:
2451    def distribute_sql(self, expression: exp.Distribute) -> str:
2452        return self.op_expressions("DISTRIBUTE BY", expression)
def sort_sql(self, expression: sqlglot.expressions.Sort) -> str:
2454    def sort_sql(self, expression: exp.Sort) -> str:
2455        return self.op_expressions("SORT BY", expression)
def ordered_sql(self, expression: sqlglot.expressions.Ordered) -> str:
2457    def ordered_sql(self, expression: exp.Ordered) -> str:
2458        desc = expression.args.get("desc")
2459        asc = not desc
2460
2461        nulls_first = expression.args.get("nulls_first")
2462        nulls_last = not nulls_first
2463        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2464        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2465        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2466
2467        this = self.sql(expression, "this")
2468
2469        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2470        nulls_sort_change = ""
2471        if nulls_first and (
2472            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2473        ):
2474            nulls_sort_change = " NULLS FIRST"
2475        elif (
2476            nulls_last
2477            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2478            and not nulls_are_last
2479        ):
2480            nulls_sort_change = " NULLS LAST"
2481
2482        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2483        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2484            window = expression.find_ancestor(exp.Window, exp.Select)
2485            if isinstance(window, exp.Window) and window.args.get("spec"):
2486                self.unsupported(
2487                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2488                )
2489                nulls_sort_change = ""
2490            elif self.NULL_ORDERING_SUPPORTED is False and (
2491                (asc and nulls_sort_change == " NULLS LAST")
2492                or (desc and nulls_sort_change == " NULLS FIRST")
2493            ):
2494                # BigQuery does not allow these ordering/nulls combinations when used under
2495                # an aggregation func or under a window containing one
2496                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2497
2498                if isinstance(ancestor, exp.Window):
2499                    ancestor = ancestor.this
2500                if isinstance(ancestor, exp.AggFunc):
2501                    self.unsupported(
2502                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2503                    )
2504                    nulls_sort_change = ""
2505            elif self.NULL_ORDERING_SUPPORTED is None:
2506                if expression.this.is_int:
2507                    self.unsupported(
2508                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2509                    )
2510                elif not isinstance(expression.this, exp.Rand):
2511                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2512                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2513                nulls_sort_change = ""
2514
2515        with_fill = self.sql(expression, "with_fill")
2516        with_fill = f" {with_fill}" if with_fill else ""
2517
2518        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
def matchrecognizemeasure_sql(self, expression: sqlglot.expressions.MatchRecognizeMeasure) -> str:
2520    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2521        window_frame = self.sql(expression, "window_frame")
2522        window_frame = f"{window_frame} " if window_frame else ""
2523
2524        this = self.sql(expression, "this")
2525
2526        return f"{window_frame}{this}"
def matchrecognize_sql(self, expression: sqlglot.expressions.MatchRecognize) -> str:
2528    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2529        partition = self.partition_by_sql(expression)
2530        order = self.sql(expression, "order")
2531        measures = self.expressions(expression, key="measures")
2532        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2533        rows = self.sql(expression, "rows")
2534        rows = self.seg(rows) if rows else ""
2535        after = self.sql(expression, "after")
2536        after = self.seg(after) if after else ""
2537        pattern = self.sql(expression, "pattern")
2538        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2539        definition_sqls = [
2540            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2541            for definition in expression.args.get("define", [])
2542        ]
2543        definitions = self.expressions(sqls=definition_sqls)
2544        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2545        body = "".join(
2546            (
2547                partition,
2548                order,
2549                measures,
2550                rows,
2551                after,
2552                pattern,
2553                define,
2554            )
2555        )
2556        alias = self.sql(expression, "alias")
2557        alias = f" {alias}" if alias else ""
2558        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
def query_modifiers(self, expression: sqlglot.expressions.Expression, *sqls: str) -> str:
2560    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2561        limit = expression.args.get("limit")
2562
2563        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2564            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2565        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2566            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2567
2568        return csv(
2569            *sqls,
2570            *[self.sql(join) for join in expression.args.get("joins") or []],
2571            self.sql(expression, "match"),
2572            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2573            self.sql(expression, "prewhere"),
2574            self.sql(expression, "where"),
2575            self.sql(expression, "connect"),
2576            self.sql(expression, "group"),
2577            self.sql(expression, "having"),
2578            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2579            self.sql(expression, "order"),
2580            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2581            *self.after_limit_modifiers(expression),
2582            self.options_modifier(expression),
2583            sep="",
2584        )
def options_modifier(self, expression: sqlglot.expressions.Expression) -> str:
2586    def options_modifier(self, expression: exp.Expression) -> str:
2587        options = self.expressions(expression, key="options")
2588        return f" {options}" if options else ""
def queryoption_sql(self, expression: sqlglot.expressions.QueryOption) -> str:
2590    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2591        self.unsupported("Unsupported query option.")
2592        return ""
def offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2594    def offset_limit_modifiers(
2595        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2596    ) -> t.List[str]:
2597        return [
2598            self.sql(expression, "offset") if fetch else self.sql(limit),
2599            self.sql(limit) if fetch else self.sql(expression, "offset"),
2600        ]
def after_limit_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]:
2602    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2603        locks = self.expressions(expression, key="locks", sep=" ")
2604        locks = f" {locks}" if locks else ""
2605        return [locks, self.sql(expression, "sample")]
def select_sql(self, expression: sqlglot.expressions.Select) -> str:
2607    def select_sql(self, expression: exp.Select) -> str:
2608        into = expression.args.get("into")
2609        if not self.SUPPORTS_SELECT_INTO and into:
2610            into.pop()
2611
2612        hint = self.sql(expression, "hint")
2613        distinct = self.sql(expression, "distinct")
2614        distinct = f" {distinct}" if distinct else ""
2615        kind = self.sql(expression, "kind")
2616
2617        limit = expression.args.get("limit")
2618        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2619            top = self.limit_sql(limit, top=True)
2620            limit.pop()
2621        else:
2622            top = ""
2623
2624        expressions = self.expressions(expression)
2625
2626        if kind:
2627            if kind in self.SELECT_KINDS:
2628                kind = f" AS {kind}"
2629            else:
2630                if kind == "STRUCT":
2631                    expressions = self.expressions(
2632                        sqls=[
2633                            self.sql(
2634                                exp.Struct(
2635                                    expressions=[
2636                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2637                                        if isinstance(e, exp.Alias)
2638                                        else e
2639                                        for e in expression.expressions
2640                                    ]
2641                                )
2642                            )
2643                        ]
2644                    )
2645                kind = ""
2646
2647        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2648        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2649
2650        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2651        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2652        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2653        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2654        sql = self.query_modifiers(
2655            expression,
2656            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2657            self.sql(expression, "into", comment=False),
2658            self.sql(expression, "from", comment=False),
2659        )
2660
2661        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2662        if expression.args.get("with"):
2663            sql = self.maybe_comment(sql, expression)
2664            expression.pop_comments()
2665
2666        sql = self.prepend_ctes(expression, sql)
2667
2668        if not self.SUPPORTS_SELECT_INTO and into:
2669            if into.args.get("temporary"):
2670                table_kind = " TEMPORARY"
2671            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2672                table_kind = " UNLOGGED"
2673            else:
2674                table_kind = ""
2675            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2676
2677        return sql
def schema_sql(self, expression: sqlglot.expressions.Schema) -> str:
2679    def schema_sql(self, expression: exp.Schema) -> str:
2680        this = self.sql(expression, "this")
2681        sql = self.schema_columns_sql(expression)
2682        return f"{this} {sql}" if this and sql else this or sql
def schema_columns_sql(self, expression: sqlglot.expressions.Schema) -> str:
2684    def schema_columns_sql(self, expression: exp.Schema) -> str:
2685        if expression.expressions:
2686            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2687        return ""
def star_sql(self, expression: sqlglot.expressions.Star) -> str:
2689    def star_sql(self, expression: exp.Star) -> str:
2690        except_ = self.expressions(expression, key="except", flat=True)
2691        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2692        replace = self.expressions(expression, key="replace", flat=True)
2693        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2694        rename = self.expressions(expression, key="rename", flat=True)
2695        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2696        return f"*{except_}{replace}{rename}"
def parameter_sql(self, expression: sqlglot.expressions.Parameter) -> str:
2698    def parameter_sql(self, expression: exp.Parameter) -> str:
2699        this = self.sql(expression, "this")
2700        return f"{self.PARAMETER_TOKEN}{this}"
def sessionparameter_sql(self, expression: sqlglot.expressions.SessionParameter) -> str:
2702    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2703        this = self.sql(expression, "this")
2704        kind = expression.text("kind")
2705        if kind:
2706            kind = f"{kind}."
2707        return f"@@{kind}{this}"
def placeholder_sql(self, expression: sqlglot.expressions.Placeholder) -> str:
2709    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2710        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
def subquery_sql(self, expression: sqlglot.expressions.Subquery, sep: str = ' AS ') -> str:
2712    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2713        alias = self.sql(expression, "alias")
2714        alias = f"{sep}{alias}" if alias else ""
2715        sample = self.sql(expression, "sample")
2716        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2717            alias = f"{sample}{alias}"
2718
2719            # Set to None so it's not generated again by self.query_modifiers()
2720            expression.set("sample", None)
2721
2722        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2723        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2724        return self.prepend_ctes(expression, sql)
def qualify_sql(self, expression: sqlglot.expressions.Qualify) -> str:
2726    def qualify_sql(self, expression: exp.Qualify) -> str:
2727        this = self.indent(self.sql(expression, "this"))
2728        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
def unnest_sql(self, expression: sqlglot.expressions.Unnest) -> str:
2730    def unnest_sql(self, expression: exp.Unnest) -> str:
2731        args = self.expressions(expression, flat=True)
2732
2733        alias = expression.args.get("alias")
2734        offset = expression.args.get("offset")
2735
2736        if self.UNNEST_WITH_ORDINALITY:
2737            if alias and isinstance(offset, exp.Expression):
2738                alias.append("columns", offset)
2739
2740        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2741            columns = alias.columns
2742            alias = self.sql(columns[0]) if columns else ""
2743        else:
2744            alias = self.sql(alias)
2745
2746        alias = f" AS {alias}" if alias else alias
2747        if self.UNNEST_WITH_ORDINALITY:
2748            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2749        else:
2750            if isinstance(offset, exp.Expression):
2751                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2752            elif offset:
2753                suffix = f"{alias} WITH OFFSET"
2754            else:
2755                suffix = alias
2756
2757        return f"UNNEST({args}){suffix}"
def prewhere_sql(self, expression: sqlglot.expressions.PreWhere) -> str:
2759    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2760        return ""
def where_sql(self, expression: sqlglot.expressions.Where) -> str:
2762    def where_sql(self, expression: exp.Where) -> str:
2763        this = self.indent(self.sql(expression, "this"))
2764        return f"{self.seg('WHERE')}{self.sep()}{this}"
def window_sql(self, expression: sqlglot.expressions.Window) -> str:
2766    def window_sql(self, expression: exp.Window) -> str:
2767        this = self.sql(expression, "this")
2768        partition = self.partition_by_sql(expression)
2769        order = expression.args.get("order")
2770        order = self.order_sql(order, flat=True) if order else ""
2771        spec = self.sql(expression, "spec")
2772        alias = self.sql(expression, "alias")
2773        over = self.sql(expression, "over") or "OVER"
2774
2775        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2776
2777        first = expression.args.get("first")
2778        if first is None:
2779            first = ""
2780        else:
2781            first = "FIRST" if first else "LAST"
2782
2783        if not partition and not order and not spec and alias:
2784            return f"{this} {alias}"
2785
2786        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
2787        return f"{this} ({args})"
def partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2789    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2790        partition = self.expressions(expression, key="partition_by", flat=True)
2791        return f"PARTITION BY {partition}" if partition else ""
def windowspec_sql(self, expression: sqlglot.expressions.WindowSpec) -> str:
2793    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2794        kind = self.sql(expression, "kind")
2795        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2796        end = (
2797            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2798            or "CURRENT ROW"
2799        )
2800        return f"{kind} BETWEEN {start} AND {end}"
def withingroup_sql(self, expression: sqlglot.expressions.WithinGroup) -> str:
2802    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2803        this = self.sql(expression, "this")
2804        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2805        return f"{this} WITHIN GROUP ({expression_sql})"
def between_sql(self, expression: sqlglot.expressions.Between) -> str:
2807    def between_sql(self, expression: exp.Between) -> str:
2808        this = self.sql(expression, "this")
2809        low = self.sql(expression, "low")
2810        high = self.sql(expression, "high")
2811        return f"{this} BETWEEN {low} AND {high}"
def bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]:
2813    def bracket_offset_expressions(
2814        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2815    ) -> t.List[exp.Expression]:
2816        return apply_index_offset(
2817            expression.this,
2818            expression.expressions,
2819            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2820            dialect=self.dialect,
2821        )
def bracket_sql(self, expression: sqlglot.expressions.Bracket) -> str:
2823    def bracket_sql(self, expression: exp.Bracket) -> str:
2824        expressions = self.bracket_offset_expressions(expression)
2825        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2826        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
def all_sql(self, expression: sqlglot.expressions.All) -> str:
2828    def all_sql(self, expression: exp.All) -> str:
2829        return f"ALL {self.wrap(expression)}"
def any_sql(self, expression: sqlglot.expressions.Any) -> str:
2831    def any_sql(self, expression: exp.Any) -> str:
2832        this = self.sql(expression, "this")
2833        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2834            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2835                this = self.wrap(this)
2836            return f"ANY{this}"
2837        return f"ANY {this}"
def exists_sql(self, expression: sqlglot.expressions.Exists) -> str:
2839    def exists_sql(self, expression: exp.Exists) -> str:
2840        return f"EXISTS{self.wrap(expression)}"
def case_sql(self, expression: sqlglot.expressions.Case) -> str:
2842    def case_sql(self, expression: exp.Case) -> str:
2843        this = self.sql(expression, "this")
2844        statements = [f"CASE {this}" if this else "CASE"]
2845
2846        for e in expression.args["ifs"]:
2847            statements.append(f"WHEN {self.sql(e, 'this')}")
2848            statements.append(f"THEN {self.sql(e, 'true')}")
2849
2850        default = self.sql(expression, "default")
2851
2852        if default:
2853            statements.append(f"ELSE {default}")
2854
2855        statements.append("END")
2856
2857        if self.pretty and self.too_wide(statements):
2858            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2859
2860        return " ".join(statements)
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
2862    def constraint_sql(self, expression: exp.Constraint) -> str:
2863        this = self.sql(expression, "this")
2864        expressions = self.expressions(expression, flat=True)
2865        return f"CONSTRAINT {this} {expressions}"
def nextvaluefor_sql(self, expression: sqlglot.expressions.NextValueFor) -> str:
2867    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2868        order = expression.args.get("order")
2869        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2870        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
def extract_sql(self, expression: sqlglot.expressions.Extract) -> str:
2872    def extract_sql(self, expression: exp.Extract) -> str:
2873        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2874        expression_sql = self.sql(expression, "expression")
2875        return f"EXTRACT({this} FROM {expression_sql})"
def trim_sql(self, expression: sqlglot.expressions.Trim) -> str:
2877    def trim_sql(self, expression: exp.Trim) -> str:
2878        trim_type = self.sql(expression, "position")
2879
2880        if trim_type == "LEADING":
2881            func_name = "LTRIM"
2882        elif trim_type == "TRAILING":
2883            func_name = "RTRIM"
2884        else:
2885            func_name = "TRIM"
2886
2887        return self.func(func_name, expression.this, expression.expression)
def convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]:
2889    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2890        args = expression.expressions
2891        if isinstance(expression, exp.ConcatWs):
2892            args = args[1:]  # Skip the delimiter
2893
2894        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2895            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2896
2897        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2898            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2899
2900        return args
def concat_sql(self, expression: sqlglot.expressions.Concat) -> str:
2902    def concat_sql(self, expression: exp.Concat) -> str:
2903        expressions = self.convert_concat_args(expression)
2904
2905        # Some dialects don't allow a single-argument CONCAT call
2906        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2907            return self.sql(expressions[0])
2908
2909        return self.func("CONCAT", *expressions)
def concatws_sql(self, expression: sqlglot.expressions.ConcatWs) -> str:
2911    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2912        return self.func(
2913            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2914        )
def check_sql(self, expression: sqlglot.expressions.Check) -> str:
2916    def check_sql(self, expression: exp.Check) -> str:
2917        this = self.sql(expression, key="this")
2918        return f"CHECK ({this})"
def foreignkey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2920    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2921        expressions = self.expressions(expression, flat=True)
2922        expressions = f" ({expressions})" if expressions else ""
2923        reference = self.sql(expression, "reference")
2924        reference = f" {reference}" if reference else ""
2925        delete = self.sql(expression, "delete")
2926        delete = f" ON DELETE {delete}" if delete else ""
2927        update = self.sql(expression, "update")
2928        update = f" ON UPDATE {update}" if update else ""
2929        options = self.expressions(expression, key="options", flat=True, sep=" ")
2930        options = f" {options}" if options else ""
2931        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
def primarykey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2933    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2934        expressions = self.expressions(expression, flat=True)
2935        options = self.expressions(expression, key="options", flat=True, sep=" ")
2936        options = f" {options}" if options else ""
2937        return f"PRIMARY KEY ({expressions}){options}"
def if_sql(self, expression: sqlglot.expressions.If) -> str:
2939    def if_sql(self, expression: exp.If) -> str:
2940        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
def matchagainst_sql(self, expression: sqlglot.expressions.MatchAgainst) -> str:
2942    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2943        modifier = expression.args.get("modifier")
2944        modifier = f" {modifier}" if modifier else ""
2945        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
def jsonkeyvalue_sql(self, expression: sqlglot.expressions.JSONKeyValue) -> str:
2947    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2948        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
def jsonpath_sql(self, expression: sqlglot.expressions.JSONPath) -> str:
2950    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2951        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2952
2953        if expression.args.get("escape"):
2954            path = self.escape_str(path)
2955
2956        if self.QUOTE_JSON_PATH:
2957            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2958
2959        return path
def json_path_part(self, expression: int | str | sqlglot.expressions.JSONPathPart) -> str:
2961    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
2962        if isinstance(expression, exp.JSONPathPart):
2963            transform = self.TRANSFORMS.get(expression.__class__)
2964            if not callable(transform):
2965                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
2966                return ""
2967
2968            return transform(self, expression)
2969
2970        if isinstance(expression, int):
2971            return str(expression)
2972
2973        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
2974            escaped = expression.replace("'", "\\'")
2975            escaped = f"\\'{expression}\\'"
2976        else:
2977            escaped = expression.replace('"', '\\"')
2978            escaped = f'"{escaped}"'
2979
2980        return escaped
def formatjson_sql(self, expression: sqlglot.expressions.FormatJson) -> str:
2982    def formatjson_sql(self, expression: exp.FormatJson) -> str:
2983        return f"{self.sql(expression, 'this')} FORMAT JSON"
def jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2985    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
2986        null_handling = expression.args.get("null_handling")
2987        null_handling = f" {null_handling}" if null_handling else ""
2988
2989        unique_keys = expression.args.get("unique_keys")
2990        if unique_keys is not None:
2991            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
2992        else:
2993            unique_keys = ""
2994
2995        return_type = self.sql(expression, "return_type")
2996        return_type = f" RETURNING {return_type}" if return_type else ""
2997        encoding = self.sql(expression, "encoding")
2998        encoding = f" ENCODING {encoding}" if encoding else ""
2999
3000        return self.func(
3001            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3002            *expression.expressions,
3003            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3004        )
def jsonobjectagg_sql(self, expression: sqlglot.expressions.JSONObjectAgg) -> str:
3006    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3007        return self.jsonobject_sql(expression)
def jsonarray_sql(self, expression: sqlglot.expressions.JSONArray) -> str:
3009    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3010        null_handling = expression.args.get("null_handling")
3011        null_handling = f" {null_handling}" if null_handling else ""
3012        return_type = self.sql(expression, "return_type")
3013        return_type = f" RETURNING {return_type}" if return_type else ""
3014        strict = " STRICT" if expression.args.get("strict") else ""
3015        return self.func(
3016            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3017        )
def jsonarrayagg_sql(self, expression: sqlglot.expressions.JSONArrayAgg) -> str:
3019    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3020        this = self.sql(expression, "this")
3021        order = self.sql(expression, "order")
3022        null_handling = expression.args.get("null_handling")
3023        null_handling = f" {null_handling}" if null_handling else ""
3024        return_type = self.sql(expression, "return_type")
3025        return_type = f" RETURNING {return_type}" if return_type else ""
3026        strict = " STRICT" if expression.args.get("strict") else ""
3027        return self.func(
3028            "JSON_ARRAYAGG",
3029            this,
3030            suffix=f"{order}{null_handling}{return_type}{strict})",
3031        )
def jsoncolumndef_sql(self, expression: sqlglot.expressions.JSONColumnDef) -> str:
3033    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3034        path = self.sql(expression, "path")
3035        path = f" PATH {path}" if path else ""
3036        nested_schema = self.sql(expression, "nested_schema")
3037
3038        if nested_schema:
3039            return f"NESTED{path} {nested_schema}"
3040
3041        this = self.sql(expression, "this")
3042        kind = self.sql(expression, "kind")
3043        kind = f" {kind}" if kind else ""
3044        return f"{this}{kind}{path}"
def jsonschema_sql(self, expression: sqlglot.expressions.JSONSchema) -> str:
3046    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3047        return self.func("COLUMNS", *expression.expressions)
def jsontable_sql(self, expression: sqlglot.expressions.JSONTable) -> str:
3049    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3050        this = self.sql(expression, "this")
3051        path = self.sql(expression, "path")
3052        path = f", {path}" if path else ""
3053        error_handling = expression.args.get("error_handling")
3054        error_handling = f" {error_handling}" if error_handling else ""
3055        empty_handling = expression.args.get("empty_handling")
3056        empty_handling = f" {empty_handling}" if empty_handling else ""
3057        schema = self.sql(expression, "schema")
3058        return self.func(
3059            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3060        )
def openjsoncolumndef_sql(self, expression: sqlglot.expressions.OpenJSONColumnDef) -> str:
3062    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3063        this = self.sql(expression, "this")
3064        kind = self.sql(expression, "kind")
3065        path = self.sql(expression, "path")
3066        path = f" {path}" if path else ""
3067        as_json = " AS JSON" if expression.args.get("as_json") else ""
3068        return f"{this} {kind}{path}{as_json}"
def openjson_sql(self, expression: sqlglot.expressions.OpenJSON) -> str:
3070    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3071        this = self.sql(expression, "this")
3072        path = self.sql(expression, "path")
3073        path = f", {path}" if path else ""
3074        expressions = self.expressions(expression)
3075        with_ = (
3076            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3077            if expressions
3078            else ""
3079        )
3080        return f"OPENJSON({this}{path}){with_}"
def in_sql(self, expression: sqlglot.expressions.In) -> str:
3082    def in_sql(self, expression: exp.In) -> str:
3083        query = expression.args.get("query")
3084        unnest = expression.args.get("unnest")
3085        field = expression.args.get("field")
3086        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3087
3088        if query:
3089            in_sql = self.sql(query)
3090        elif unnest:
3091            in_sql = self.in_unnest_op(unnest)
3092        elif field:
3093            in_sql = self.sql(field)
3094        else:
3095            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3096
3097        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
def in_unnest_op(self, unnest: sqlglot.expressions.Unnest) -> str:
3099    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3100        return f"(SELECT {self.sql(unnest)})"
def interval_sql(self, expression: sqlglot.expressions.Interval) -> str:
3102    def interval_sql(self, expression: exp.Interval) -> str:
3103        unit = self.sql(expression, "unit")
3104        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3105            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3106        unit = f" {unit}" if unit else ""
3107
3108        if self.SINGLE_STRING_INTERVAL:
3109            this = expression.this.name if expression.this else ""
3110            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3111
3112        this = self.sql(expression, "this")
3113        if this:
3114            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3115            this = f" {this}" if unwrapped else f" ({this})"
3116
3117        return f"INTERVAL{this}{unit}"
def return_sql(self, expression: sqlglot.expressions.Return) -> str:
3119    def return_sql(self, expression: exp.Return) -> str:
3120        return f"RETURN {self.sql(expression, 'this')}"
def reference_sql(self, expression: sqlglot.expressions.Reference) -> str:
3122    def reference_sql(self, expression: exp.Reference) -> str:
3123        this = self.sql(expression, "this")
3124        expressions = self.expressions(expression, flat=True)
3125        expressions = f"({expressions})" if expressions else ""
3126        options = self.expressions(expression, key="options", flat=True, sep=" ")
3127        options = f" {options}" if options else ""
3128        return f"REFERENCES {this}{expressions}{options}"
def anonymous_sql(self, expression: sqlglot.expressions.Anonymous) -> str:
3130    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3131        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3132        parent = expression.parent
3133        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3134        return self.func(
3135            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3136        )
def paren_sql(self, expression: sqlglot.expressions.Paren) -> str:
3138    def paren_sql(self, expression: exp.Paren) -> str:
3139        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3140        return f"({sql}{self.seg(')', sep='')}"
def neg_sql(self, expression: sqlglot.expressions.Neg) -> str:
3142    def neg_sql(self, expression: exp.Neg) -> str:
3143        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3144        this_sql = self.sql(expression, "this")
3145        sep = " " if this_sql[0] == "-" else ""
3146        return f"-{sep}{this_sql}"
def not_sql(self, expression: sqlglot.expressions.Not) -> str:
3148    def not_sql(self, expression: exp.Not) -> str:
3149        return f"NOT {self.sql(expression, 'this')}"
def alias_sql(self, expression: sqlglot.expressions.Alias) -> str:
3151    def alias_sql(self, expression: exp.Alias) -> str:
3152        alias = self.sql(expression, "alias")
3153        alias = f" AS {alias}" if alias else ""
3154        return f"{self.sql(expression, 'this')}{alias}"
def pivotalias_sql(self, expression: sqlglot.expressions.PivotAlias) -> str:
3156    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3157        alias = expression.args["alias"]
3158
3159        parent = expression.parent
3160        pivot = parent and parent.parent
3161
3162        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3163            identifier_alias = isinstance(alias, exp.Identifier)
3164            literal_alias = isinstance(alias, exp.Literal)
3165
3166            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3167                alias.replace(exp.Literal.string(alias.output_name))
3168            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3169                alias.replace(exp.to_identifier(alias.output_name))
3170
3171        return self.alias_sql(expression)
def aliases_sql(self, expression: sqlglot.expressions.Aliases) -> str:
3173    def aliases_sql(self, expression: exp.Aliases) -> str:
3174        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
def atindex_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3176    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3177        this = self.sql(expression, "this")
3178        index = self.sql(expression, "expression")
3179        return f"{this} AT {index}"
def attimezone_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3181    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3182        this = self.sql(expression, "this")
3183        zone = self.sql(expression, "zone")
3184        return f"{this} AT TIME ZONE {zone}"
def fromtimezone_sql(self, expression: sqlglot.expressions.FromTimeZone) -> str:
3186    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3187        this = self.sql(expression, "this")
3188        zone = self.sql(expression, "zone")
3189        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
def add_sql(self, expression: sqlglot.expressions.Add) -> str:
3191    def add_sql(self, expression: exp.Add) -> str:
3192        return self.binary(expression, "+")
def and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3194    def and_sql(
3195        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3196    ) -> str:
3197        return self.connector_sql(expression, "AND", stack)
def or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3199    def or_sql(
3200        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3201    ) -> str:
3202        return self.connector_sql(expression, "OR", stack)
def xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3204    def xor_sql(
3205        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3206    ) -> str:
3207        return self.connector_sql(expression, "XOR", stack)
def connector_sql( self, expression: sqlglot.expressions.Connector, op: str, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3209    def connector_sql(
3210        self,
3211        expression: exp.Connector,
3212        op: str,
3213        stack: t.Optional[t.List[str | exp.Expression]] = None,
3214    ) -> str:
3215        if stack is not None:
3216            if expression.expressions:
3217                stack.append(self.expressions(expression, sep=f" {op} "))
3218            else:
3219                stack.append(expression.right)
3220                if expression.comments and self.comments:
3221                    for comment in expression.comments:
3222                        if comment:
3223                            op += f" /*{self.pad_comment(comment)}*/"
3224                stack.extend((op, expression.left))
3225            return op
3226
3227        stack = [expression]
3228        sqls: t.List[str] = []
3229        ops = set()
3230
3231        while stack:
3232            node = stack.pop()
3233            if isinstance(node, exp.Connector):
3234                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3235            else:
3236                sql = self.sql(node)
3237                if sqls and sqls[-1] in ops:
3238                    sqls[-1] += f" {sql}"
3239                else:
3240                    sqls.append(sql)
3241
3242        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3243        return sep.join(sqls)
def bitwiseand_sql(self, expression: sqlglot.expressions.BitwiseAnd) -> str:
3245    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3246        return self.binary(expression, "&")
def bitwiseleftshift_sql(self, expression: sqlglot.expressions.BitwiseLeftShift) -> str:
3248    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3249        return self.binary(expression, "<<")
def bitwisenot_sql(self, expression: sqlglot.expressions.BitwiseNot) -> str:
3251    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3252        return f"~{self.sql(expression, 'this')}"
def bitwiseor_sql(self, expression: sqlglot.expressions.BitwiseOr) -> str:
3254    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3255        return self.binary(expression, "|")
def bitwiserightshift_sql(self, expression: sqlglot.expressions.BitwiseRightShift) -> str:
3257    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3258        return self.binary(expression, ">>")
def bitwisexor_sql(self, expression: sqlglot.expressions.BitwiseXor) -> str:
3260    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3261        return self.binary(expression, "^")
def cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3263    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3264        format_sql = self.sql(expression, "format")
3265        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3266        to_sql = self.sql(expression, "to")
3267        to_sql = f" {to_sql}" if to_sql else ""
3268        action = self.sql(expression, "action")
3269        action = f" {action}" if action else ""
3270        default = self.sql(expression, "default")
3271        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3272        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
def currentdate_sql(self, expression: sqlglot.expressions.CurrentDate) -> str:
3274    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3275        zone = self.sql(expression, "this")
3276        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
def collate_sql(self, expression: sqlglot.expressions.Collate) -> str:
3278    def collate_sql(self, expression: exp.Collate) -> str:
3279        if self.COLLATE_IS_FUNC:
3280            return self.function_fallback_sql(expression)
3281        return self.binary(expression, "COLLATE")
def command_sql(self, expression: sqlglot.expressions.Command) -> str:
3283    def command_sql(self, expression: exp.Command) -> str:
3284        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
def comment_sql(self, expression: sqlglot.expressions.Comment) -> str:
3286    def comment_sql(self, expression: exp.Comment) -> str:
3287        this = self.sql(expression, "this")
3288        kind = expression.args["kind"]
3289        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3290        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3291        expression_sql = self.sql(expression, "expression")
3292        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
def mergetreettlaction_sql(self, expression: sqlglot.expressions.MergeTreeTTLAction) -> str:
3294    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3295        this = self.sql(expression, "this")
3296        delete = " DELETE" if expression.args.get("delete") else ""
3297        recompress = self.sql(expression, "recompress")
3298        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3299        to_disk = self.sql(expression, "to_disk")
3300        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3301        to_volume = self.sql(expression, "to_volume")
3302        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3303        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
def mergetreettl_sql(self, expression: sqlglot.expressions.MergeTreeTTL) -> str:
3305    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3306        where = self.sql(expression, "where")
3307        group = self.sql(expression, "group")
3308        aggregates = self.expressions(expression, key="aggregates")
3309        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3310
3311        if not (where or group or aggregates) and len(expression.expressions) == 1:
3312            return f"TTL {self.expressions(expression, flat=True)}"
3313
3314        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
3316    def transaction_sql(self, expression: exp.Transaction) -> str:
3317        return "BEGIN"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
3319    def commit_sql(self, expression: exp.Commit) -> str:
3320        chain = expression.args.get("chain")
3321        if chain is not None:
3322            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3323
3324        return f"COMMIT{chain or ''}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
3326    def rollback_sql(self, expression: exp.Rollback) -> str:
3327        savepoint = expression.args.get("savepoint")
3328        savepoint = f" TO {savepoint}" if savepoint else ""
3329        return f"ROLLBACK{savepoint}"
def altercolumn_sql(self, expression: sqlglot.expressions.AlterColumn) -> str:
3331    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3332        this = self.sql(expression, "this")
3333
3334        dtype = self.sql(expression, "dtype")
3335        if dtype:
3336            collate = self.sql(expression, "collate")
3337            collate = f" COLLATE {collate}" if collate else ""
3338            using = self.sql(expression, "using")
3339            using = f" USING {using}" if using else ""
3340            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
3341
3342        default = self.sql(expression, "default")
3343        if default:
3344            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3345
3346        comment = self.sql(expression, "comment")
3347        if comment:
3348            return f"ALTER COLUMN {this} COMMENT {comment}"
3349
3350        visible = expression.args.get("visible")
3351        if visible:
3352            return f"ALTER COLUMN {this} SET {visible}"
3353
3354        allow_null = expression.args.get("allow_null")
3355        drop = expression.args.get("drop")
3356
3357        if not drop and not allow_null:
3358            self.unsupported("Unsupported ALTER COLUMN syntax")
3359
3360        if allow_null is not None:
3361            keyword = "DROP" if drop else "SET"
3362            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3363
3364        return f"ALTER COLUMN {this} DROP DEFAULT"
def alterindex_sql(self, expression: sqlglot.expressions.AlterIndex) -> str:
3366    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3367        this = self.sql(expression, "this")
3368
3369        visible = expression.args.get("visible")
3370        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3371
3372        return f"ALTER INDEX {this} {visible_sql}"
def alterdiststyle_sql(self, expression: sqlglot.expressions.AlterDistStyle) -> str:
3374    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3375        this = self.sql(expression, "this")
3376        if not isinstance(expression.this, exp.Var):
3377            this = f"KEY DISTKEY {this}"
3378        return f"ALTER DISTSTYLE {this}"
def altersortkey_sql(self, expression: sqlglot.expressions.AlterSortKey) -> str:
3380    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3381        compound = " COMPOUND" if expression.args.get("compound") else ""
3382        this = self.sql(expression, "this")
3383        expressions = self.expressions(expression, flat=True)
3384        expressions = f"({expressions})" if expressions else ""
3385        return f"ALTER{compound} SORTKEY {this or expressions}"
def alterrename_sql(self, expression: sqlglot.expressions.AlterRename) -> str:
3387    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3388        if not self.RENAME_TABLE_WITH_DB:
3389            # Remove db from tables
3390            expression = expression.transform(
3391                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3392            ).assert_is(exp.AlterRename)
3393        this = self.sql(expression, "this")
3394        return f"RENAME TO {this}"
def renamecolumn_sql(self, expression: sqlglot.expressions.RenameColumn) -> str:
3396    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3397        exists = " IF EXISTS" if expression.args.get("exists") else ""
3398        old_column = self.sql(expression, "this")
3399        new_column = self.sql(expression, "to")
3400        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
def alterset_sql(self, expression: sqlglot.expressions.AlterSet) -> str:
3402    def alterset_sql(self, expression: exp.AlterSet) -> str:
3403        exprs = self.expressions(expression, flat=True)
3404        return f"SET {exprs}"
def alter_sql(self, expression: sqlglot.expressions.Alter) -> str:
3406    def alter_sql(self, expression: exp.Alter) -> str:
3407        actions = expression.args["actions"]
3408
3409        if isinstance(actions[0], exp.ColumnDef):
3410            actions = self.add_column_sql(expression)
3411        elif isinstance(actions[0], exp.Schema):
3412            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
3413        elif isinstance(actions[0], exp.Delete):
3414            actions = self.expressions(expression, key="actions", flat=True)
3415        elif isinstance(actions[0], exp.Query):
3416            actions = "AS " + self.expressions(expression, key="actions")
3417        else:
3418            actions = self.expressions(expression, key="actions", flat=True)
3419
3420        exists = " IF EXISTS" if expression.args.get("exists") else ""
3421        on_cluster = self.sql(expression, "cluster")
3422        on_cluster = f" {on_cluster}" if on_cluster else ""
3423        only = " ONLY" if expression.args.get("only") else ""
3424        options = self.expressions(expression, key="options")
3425        options = f", {options}" if options else ""
3426        kind = self.sql(expression, "kind")
3427        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3428
3429        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
def add_column_sql(self, expression: sqlglot.expressions.Alter) -> str:
3431    def add_column_sql(self, expression: exp.Alter) -> str:
3432        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3433            return self.expressions(
3434                expression,
3435                key="actions",
3436                prefix="ADD COLUMN ",
3437                skip_first=True,
3438            )
3439        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
def droppartition_sql(self, expression: sqlglot.expressions.DropPartition) -> str:
3441    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3442        expressions = self.expressions(expression)
3443        exists = " IF EXISTS " if expression.args.get("exists") else " "
3444        return f"DROP{exists}{expressions}"
def addconstraint_sql(self, expression: sqlglot.expressions.AddConstraint) -> str:
3446    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3447        return f"ADD {self.expressions(expression)}"
def distinct_sql(self, expression: sqlglot.expressions.Distinct) -> str:
3449    def distinct_sql(self, expression: exp.Distinct) -> str:
3450        this = self.expressions(expression, flat=True)
3451
3452        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3453            case = exp.case()
3454            for arg in expression.expressions:
3455                case = case.when(arg.is_(exp.null()), exp.null())
3456            this = self.sql(case.else_(f"({this})"))
3457
3458        this = f" {this}" if this else ""
3459
3460        on = self.sql(expression, "on")
3461        on = f" ON {on}" if on else ""
3462        return f"DISTINCT{this}{on}"
def ignorenulls_sql(self, expression: sqlglot.expressions.IgnoreNulls) -> str:
3464    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3465        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
def respectnulls_sql(self, expression: sqlglot.expressions.RespectNulls) -> str:
3467    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3468        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
def havingmax_sql(self, expression: sqlglot.expressions.HavingMax) -> str:
3470    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3471        this_sql = self.sql(expression, "this")
3472        expression_sql = self.sql(expression, "expression")
3473        kind = "MAX" if expression.args.get("max") else "MIN"
3474        return f"{this_sql} HAVING {kind} {expression_sql}"
def intdiv_sql(self, expression: sqlglot.expressions.IntDiv) -> str:
3476    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3477        return self.sql(
3478            exp.Cast(
3479                this=exp.Div(this=expression.this, expression=expression.expression),
3480                to=exp.DataType(this=exp.DataType.Type.INT),
3481            )
3482        )
def dpipe_sql(self, expression: sqlglot.expressions.DPipe) -> str:
3484    def dpipe_sql(self, expression: exp.DPipe) -> str:
3485        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3486            return self.func(
3487                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3488            )
3489        return self.binary(expression, "||")
def div_sql(self, expression: sqlglot.expressions.Div) -> str:
3491    def div_sql(self, expression: exp.Div) -> str:
3492        l, r = expression.left, expression.right
3493
3494        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3495            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3496
3497        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3498            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3499                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3500
3501        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3502            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3503                return self.sql(
3504                    exp.cast(
3505                        l / r,
3506                        to=exp.DataType.Type.BIGINT,
3507                    )
3508                )
3509
3510        return self.binary(expression, "/")
def safedivide_sql(self, expression: sqlglot.expressions.SafeDivide) -> str:
3512    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3513        n = exp._wrap(expression.this, exp.Binary)
3514        d = exp._wrap(expression.expression, exp.Binary)
3515        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
def overlaps_sql(self, expression: sqlglot.expressions.Overlaps) -> str:
3517    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3518        return self.binary(expression, "OVERLAPS")
def distance_sql(self, expression: sqlglot.expressions.Distance) -> str:
3520    def distance_sql(self, expression: exp.Distance) -> str:
3521        return self.binary(expression, "<->")
def dot_sql(self, expression: sqlglot.expressions.Dot) -> str:
3523    def dot_sql(self, expression: exp.Dot) -> str:
3524        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
def eq_sql(self, expression: sqlglot.expressions.EQ) -> str:
3526    def eq_sql(self, expression: exp.EQ) -> str:
3527        return self.binary(expression, "=")
def propertyeq_sql(self, expression: sqlglot.expressions.PropertyEQ) -> str:
3529    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3530        return self.binary(expression, ":=")
def escape_sql(self, expression: sqlglot.expressions.Escape) -> str:
3532    def escape_sql(self, expression: exp.Escape) -> str:
3533        return self.binary(expression, "ESCAPE")
def glob_sql(self, expression: sqlglot.expressions.Glob) -> str:
3535    def glob_sql(self, expression: exp.Glob) -> str:
3536        return self.binary(expression, "GLOB")
def gt_sql(self, expression: sqlglot.expressions.GT) -> str:
3538    def gt_sql(self, expression: exp.GT) -> str:
3539        return self.binary(expression, ">")
def gte_sql(self, expression: sqlglot.expressions.GTE) -> str:
3541    def gte_sql(self, expression: exp.GTE) -> str:
3542        return self.binary(expression, ">=")
def ilike_sql(self, expression: sqlglot.expressions.ILike) -> str:
3544    def ilike_sql(self, expression: exp.ILike) -> str:
3545        return self.binary(expression, "ILIKE")
def ilikeany_sql(self, expression: sqlglot.expressions.ILikeAny) -> str:
3547    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3548        return self.binary(expression, "ILIKE ANY")
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
3550    def is_sql(self, expression: exp.Is) -> str:
3551        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3552            return self.sql(
3553                expression.this if expression.expression.this else exp.not_(expression.this)
3554            )
3555        return self.binary(expression, "IS")
def like_sql(self, expression: sqlglot.expressions.Like) -> str:
3557    def like_sql(self, expression: exp.Like) -> str:
3558        return self.binary(expression, "LIKE")
def likeany_sql(self, expression: sqlglot.expressions.LikeAny) -> str:
3560    def likeany_sql(self, expression: exp.LikeAny) -> str:
3561        return self.binary(expression, "LIKE ANY")
def similarto_sql(self, expression: sqlglot.expressions.SimilarTo) -> str:
3563    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3564        return self.binary(expression, "SIMILAR TO")
def lt_sql(self, expression: sqlglot.expressions.LT) -> str:
3566    def lt_sql(self, expression: exp.LT) -> str:
3567        return self.binary(expression, "<")
def lte_sql(self, expression: sqlglot.expressions.LTE) -> str:
3569    def lte_sql(self, expression: exp.LTE) -> str:
3570        return self.binary(expression, "<=")
def mod_sql(self, expression: sqlglot.expressions.Mod) -> str:
3572    def mod_sql(self, expression: exp.Mod) -> str:
3573        return self.binary(expression, "%")
def mul_sql(self, expression: sqlglot.expressions.Mul) -> str:
3575    def mul_sql(self, expression: exp.Mul) -> str:
3576        return self.binary(expression, "*")
def neq_sql(self, expression: sqlglot.expressions.NEQ) -> str:
3578    def neq_sql(self, expression: exp.NEQ) -> str:
3579        return self.binary(expression, "<>")
def nullsafeeq_sql(self, expression: sqlglot.expressions.NullSafeEQ) -> str:
3581    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3582        return self.binary(expression, "IS NOT DISTINCT FROM")
def nullsafeneq_sql(self, expression: sqlglot.expressions.NullSafeNEQ) -> str:
3584    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3585        return self.binary(expression, "IS DISTINCT FROM")
def slice_sql(self, expression: sqlglot.expressions.Slice) -> str:
3587    def slice_sql(self, expression: exp.Slice) -> str:
3588        return self.binary(expression, ":")
def sub_sql(self, expression: sqlglot.expressions.Sub) -> str:
3590    def sub_sql(self, expression: exp.Sub) -> str:
3591        return self.binary(expression, "-")
def trycast_sql(self, expression: sqlglot.expressions.TryCast) -> str:
3593    def trycast_sql(self, expression: exp.TryCast) -> str:
3594        return self.cast_sql(expression, safe_prefix="TRY_")
def jsoncast_sql(self, expression: sqlglot.expressions.JSONCast) -> str:
3596    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3597        return self.cast_sql(expression)
def try_sql(self, expression: sqlglot.expressions.Try) -> str:
3599    def try_sql(self, expression: exp.Try) -> str:
3600        if not self.TRY_SUPPORTED:
3601            self.unsupported("Unsupported TRY function")
3602            return self.sql(expression, "this")
3603
3604        return self.func("TRY", expression.this)
def log_sql(self, expression: sqlglot.expressions.Log) -> str:
3606    def log_sql(self, expression: exp.Log) -> str:
3607        this = expression.this
3608        expr = expression.expression
3609
3610        if self.dialect.LOG_BASE_FIRST is False:
3611            this, expr = expr, this
3612        elif self.dialect.LOG_BASE_FIRST is None and expr:
3613            if this.name in ("2", "10"):
3614                return self.func(f"LOG{this.name}", expr)
3615
3616            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3617
3618        return self.func("LOG", this, expr)
def use_sql(self, expression: sqlglot.expressions.Use) -> str:
3620    def use_sql(self, expression: exp.Use) -> str:
3621        kind = self.sql(expression, "kind")
3622        kind = f" {kind}" if kind else ""
3623        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3624        this = f" {this}" if this else ""
3625        return f"USE{kind}{this}"
def binary(self, expression: sqlglot.expressions.Binary, op: str) -> str:
3627    def binary(self, expression: exp.Binary, op: str) -> str:
3628        sqls: t.List[str] = []
3629        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3630        binary_type = type(expression)
3631
3632        while stack:
3633            node = stack.pop()
3634
3635            if type(node) is binary_type:
3636                op_func = node.args.get("operator")
3637                if op_func:
3638                    op = f"OPERATOR({self.sql(op_func)})"
3639
3640                stack.append(node.right)
3641                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3642                stack.append(node.left)
3643            else:
3644                sqls.append(self.sql(node))
3645
3646        return "".join(sqls)
def ceil_floor( self, expression: sqlglot.expressions.Ceil | sqlglot.expressions.Floor) -> str:
3648    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3649        to_clause = self.sql(expression, "to")
3650        if to_clause:
3651            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3652
3653        return self.function_fallback_sql(expression)
def function_fallback_sql(self, expression: sqlglot.expressions.Func) -> str:
3655    def function_fallback_sql(self, expression: exp.Func) -> str:
3656        args = []
3657
3658        for key in expression.arg_types:
3659            arg_value = expression.args.get(key)
3660
3661            if isinstance(arg_value, list):
3662                for value in arg_value:
3663                    args.append(value)
3664            elif arg_value is not None:
3665                args.append(arg_value)
3666
3667        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3668            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3669        else:
3670            name = expression.sql_name()
3671
3672        return self.func(name, *args)
def func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')', normalize: bool = True) -> str:
3674    def func(
3675        self,
3676        name: str,
3677        *args: t.Optional[exp.Expression | str],
3678        prefix: str = "(",
3679        suffix: str = ")",
3680        normalize: bool = True,
3681    ) -> str:
3682        name = self.normalize_func(name) if normalize else name
3683        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3685    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3686        arg_sqls = tuple(
3687            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3688        )
3689        if self.pretty and self.too_wide(arg_sqls):
3690            return self.indent(
3691                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3692            )
3693        return sep.join(arg_sqls)
def too_wide(self, args: Iterable) -> bool:
3695    def too_wide(self, args: t.Iterable) -> bool:
3696        return sum(len(arg) for arg in args) > self.max_text_width
def format_time( self, expression: sqlglot.expressions.Expression, inverse_time_mapping: Optional[Dict[str, str]] = None, inverse_time_trie: Optional[Dict] = None) -> Optional[str]:
3698    def format_time(
3699        self,
3700        expression: exp.Expression,
3701        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3702        inverse_time_trie: t.Optional[t.Dict] = None,
3703    ) -> t.Optional[str]:
3704        return format_time(
3705            self.sql(expression, "format"),
3706            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3707            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3708        )
def expressions( self, expression: Optional[sqlglot.expressions.Expression] = None, key: Optional[str] = None, sqls: Optional[Collection[Union[str, sqlglot.expressions.Expression]]] = None, flat: bool = False, indent: bool = True, skip_first: bool = False, skip_last: bool = False, sep: str = ', ', prefix: str = '', dynamic: bool = False, new_line: bool = False) -> str:
3710    def expressions(
3711        self,
3712        expression: t.Optional[exp.Expression] = None,
3713        key: t.Optional[str] = None,
3714        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3715        flat: bool = False,
3716        indent: bool = True,
3717        skip_first: bool = False,
3718        skip_last: bool = False,
3719        sep: str = ", ",
3720        prefix: str = "",
3721        dynamic: bool = False,
3722        new_line: bool = False,
3723    ) -> str:
3724        expressions = expression.args.get(key or "expressions") if expression else sqls
3725
3726        if not expressions:
3727            return ""
3728
3729        if flat:
3730            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3731
3732        num_sqls = len(expressions)
3733        result_sqls = []
3734
3735        for i, e in enumerate(expressions):
3736            sql = self.sql(e, comment=False)
3737            if not sql:
3738                continue
3739
3740            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3741
3742            if self.pretty:
3743                if self.leading_comma:
3744                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3745                else:
3746                    result_sqls.append(
3747                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3748                    )
3749            else:
3750                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3751
3752        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3753            if new_line:
3754                result_sqls.insert(0, "")
3755                result_sqls.append("")
3756            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3757        else:
3758            result_sql = "".join(result_sqls)
3759
3760        return (
3761            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3762            if indent
3763            else result_sql
3764        )
def op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3766    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3767        flat = flat or isinstance(expression.parent, exp.Properties)
3768        expressions_sql = self.expressions(expression, flat=flat)
3769        if flat:
3770            return f"{op} {expressions_sql}"
3771        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
def naked_property(self, expression: sqlglot.expressions.Property) -> str:
3773    def naked_property(self, expression: exp.Property) -> str:
3774        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3775        if not property_name:
3776            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3777        return f"{property_name} {self.sql(expression, 'this')}"
def tag_sql(self, expression: sqlglot.expressions.Tag) -> str:
3779    def tag_sql(self, expression: exp.Tag) -> str:
3780        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
def token_sql(self, token_type: sqlglot.tokens.TokenType) -> str:
3782    def token_sql(self, token_type: TokenType) -> str:
3783        return self.TOKEN_MAPPING.get(token_type, token_type.name)
def userdefinedfunction_sql(self, expression: sqlglot.expressions.UserDefinedFunction) -> str:
3785    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3786        this = self.sql(expression, "this")
3787        expressions = self.no_identify(self.expressions, expression)
3788        expressions = (
3789            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3790        )
3791        return f"{this}{expressions}" if expressions.strip() != "" else this
def joinhint_sql(self, expression: sqlglot.expressions.JoinHint) -> str:
3793    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3794        this = self.sql(expression, "this")
3795        expressions = self.expressions(expression, flat=True)
3796        return f"{this}({expressions})"
def kwarg_sql(self, expression: sqlglot.expressions.Kwarg) -> str:
3798    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3799        return self.binary(expression, "=>")
def when_sql(self, expression: sqlglot.expressions.When) -> str:
3801    def when_sql(self, expression: exp.When) -> str:
3802        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3803        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3804        condition = self.sql(expression, "condition")
3805        condition = f" AND {condition}" if condition else ""
3806
3807        then_expression = expression.args.get("then")
3808        if isinstance(then_expression, exp.Insert):
3809            this = self.sql(then_expression, "this")
3810            this = f"INSERT {this}" if this else "INSERT"
3811            then = self.sql(then_expression, "expression")
3812            then = f"{this} VALUES {then}" if then else this
3813        elif isinstance(then_expression, exp.Update):
3814            if isinstance(then_expression.args.get("expressions"), exp.Star):
3815                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3816            else:
3817                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
3818        else:
3819            then = self.sql(then_expression)
3820        return f"WHEN {matched}{source}{condition} THEN {then}"
def whens_sql(self, expression: sqlglot.expressions.Whens) -> str:
3822    def whens_sql(self, expression: exp.Whens) -> str:
3823        return self.expressions(expression, sep=" ", indent=False)
def merge_sql(self, expression: sqlglot.expressions.Merge) -> str:
3825    def merge_sql(self, expression: exp.Merge) -> str:
3826        table = expression.this
3827        table_alias = ""
3828
3829        hints = table.args.get("hints")
3830        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3831            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3832            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3833
3834        this = self.sql(table)
3835        using = f"USING {self.sql(expression, 'using')}"
3836        on = f"ON {self.sql(expression, 'on')}"
3837        whens = self.sql(expression, "whens")
3838
3839        returning = self.sql(expression, "returning")
3840        if returning:
3841            whens = f"{whens}{returning}"
3842
3843        sep = self.sep()
3844
3845        return self.prepend_ctes(
3846            expression,
3847            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3848        )
@unsupported_args('format')
def tochar_sql(self, expression: sqlglot.expressions.ToChar) -> str:
3850    @unsupported_args("format")
3851    def tochar_sql(self, expression: exp.ToChar) -> str:
3852        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
def tonumber_sql(self, expression: sqlglot.expressions.ToNumber) -> str:
3854    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3855        if not self.SUPPORTS_TO_NUMBER:
3856            self.unsupported("Unsupported TO_NUMBER function")
3857            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3858
3859        fmt = expression.args.get("format")
3860        if not fmt:
3861            self.unsupported("Conversion format is required for TO_NUMBER")
3862            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3863
3864        return self.func("TO_NUMBER", expression.this, fmt)
def dictproperty_sql(self, expression: sqlglot.expressions.DictProperty) -> str:
3866    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3867        this = self.sql(expression, "this")
3868        kind = self.sql(expression, "kind")
3869        settings_sql = self.expressions(expression, key="settings", sep=" ")
3870        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3871        return f"{this}({kind}{args})"
def dictrange_sql(self, expression: sqlglot.expressions.DictRange) -> str:
3873    def dictrange_sql(self, expression: exp.DictRange) -> str:
3874        this = self.sql(expression, "this")
3875        max = self.sql(expression, "max")
3876        min = self.sql(expression, "min")
3877        return f"{this}(MIN {min} MAX {max})"
def dictsubproperty_sql(self, expression: sqlglot.expressions.DictSubProperty) -> str:
3879    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3880        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
def duplicatekeyproperty_sql(self, expression: sqlglot.expressions.DuplicateKeyProperty) -> str:
3882    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3883        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
def uniquekeyproperty_sql(self, expression: sqlglot.expressions.UniqueKeyProperty) -> str:
3886    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3887        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
def distributedbyproperty_sql(self, expression: sqlglot.expressions.DistributedByProperty) -> str:
3890    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3891        expressions = self.expressions(expression, flat=True)
3892        expressions = f" {self.wrap(expressions)}" if expressions else ""
3893        buckets = self.sql(expression, "buckets")
3894        kind = self.sql(expression, "kind")
3895        buckets = f" BUCKETS {buckets}" if buckets else ""
3896        order = self.sql(expression, "order")
3897        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
def oncluster_sql(self, expression: sqlglot.expressions.OnCluster) -> str:
3899    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3900        return ""
def clusteredbyproperty_sql(self, expression: sqlglot.expressions.ClusteredByProperty) -> str:
3902    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3903        expressions = self.expressions(expression, key="expressions", flat=True)
3904        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3905        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3906        buckets = self.sql(expression, "buckets")
3907        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
def anyvalue_sql(self, expression: sqlglot.expressions.AnyValue) -> str:
3909    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3910        this = self.sql(expression, "this")
3911        having = self.sql(expression, "having")
3912
3913        if having:
3914            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3915
3916        return self.func("ANY_VALUE", this)
def querytransform_sql(self, expression: sqlglot.expressions.QueryTransform) -> str:
3918    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3919        transform = self.func("TRANSFORM", *expression.expressions)
3920        row_format_before = self.sql(expression, "row_format_before")
3921        row_format_before = f" {row_format_before}" if row_format_before else ""
3922        record_writer = self.sql(expression, "record_writer")
3923        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3924        using = f" USING {self.sql(expression, 'command_script')}"
3925        schema = self.sql(expression, "schema")
3926        schema = f" AS {schema}" if schema else ""
3927        row_format_after = self.sql(expression, "row_format_after")
3928        row_format_after = f" {row_format_after}" if row_format_after else ""
3929        record_reader = self.sql(expression, "record_reader")
3930        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3931        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
def indexconstraintoption_sql(self, expression: sqlglot.expressions.IndexConstraintOption) -> str:
3933    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3934        key_block_size = self.sql(expression, "key_block_size")
3935        if key_block_size:
3936            return f"KEY_BLOCK_SIZE = {key_block_size}"
3937
3938        using = self.sql(expression, "using")
3939        if using:
3940            return f"USING {using}"
3941
3942        parser = self.sql(expression, "parser")
3943        if parser:
3944            return f"WITH PARSER {parser}"
3945
3946        comment = self.sql(expression, "comment")
3947        if comment:
3948            return f"COMMENT {comment}"
3949
3950        visible = expression.args.get("visible")
3951        if visible is not None:
3952            return "VISIBLE" if visible else "INVISIBLE"
3953
3954        engine_attr = self.sql(expression, "engine_attr")
3955        if engine_attr:
3956            return f"ENGINE_ATTRIBUTE = {engine_attr}"
3957
3958        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
3959        if secondary_engine_attr:
3960            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
3961
3962        self.unsupported("Unsupported index constraint option.")
3963        return ""
def checkcolumnconstraint_sql(self, expression: sqlglot.expressions.CheckColumnConstraint) -> str:
3965    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
3966        enforced = " ENFORCED" if expression.args.get("enforced") else ""
3967        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
def indexcolumnconstraint_sql(self, expression: sqlglot.expressions.IndexColumnConstraint) -> str:
3969    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
3970        kind = self.sql(expression, "kind")
3971        kind = f"{kind} INDEX" if kind else "INDEX"
3972        this = self.sql(expression, "this")
3973        this = f" {this}" if this else ""
3974        index_type = self.sql(expression, "index_type")
3975        index_type = f" USING {index_type}" if index_type else ""
3976        expressions = self.expressions(expression, flat=True)
3977        expressions = f" ({expressions})" if expressions else ""
3978        options = self.expressions(expression, key="options", sep=" ")
3979        options = f" {options}" if options else ""
3980        return f"{kind}{this}{index_type}{expressions}{options}"
def nvl2_sql(self, expression: sqlglot.expressions.Nvl2) -> str:
3982    def nvl2_sql(self, expression: exp.Nvl2) -> str:
3983        if self.NVL2_SUPPORTED:
3984            return self.function_fallback_sql(expression)
3985
3986        case = exp.Case().when(
3987            expression.this.is_(exp.null()).not_(copy=False),
3988            expression.args["true"],
3989            copy=False,
3990        )
3991        else_cond = expression.args.get("false")
3992        if else_cond:
3993            case.else_(else_cond, copy=False)
3994
3995        return self.sql(case)
def comprehension_sql(self, expression: sqlglot.expressions.Comprehension) -> str:
3997    def comprehension_sql(self, expression: exp.Comprehension) -> str:
3998        this = self.sql(expression, "this")
3999        expr = self.sql(expression, "expression")
4000        iterator = self.sql(expression, "iterator")
4001        condition = self.sql(expression, "condition")
4002        condition = f" IF {condition}" if condition else ""
4003        return f"{this} FOR {expr} IN {iterator}{condition}"
def columnprefix_sql(self, expression: sqlglot.expressions.ColumnPrefix) -> str:
4005    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4006        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
def opclass_sql(self, expression: sqlglot.expressions.Opclass) -> str:
4008    def opclass_sql(self, expression: exp.Opclass) -> str:
4009        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def predict_sql(self, expression: sqlglot.expressions.Predict) -> str:
4011    def predict_sql(self, expression: exp.Predict) -> str:
4012        model = self.sql(expression, "this")
4013        model = f"MODEL {model}"
4014        table = self.sql(expression, "expression")
4015        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4016        parameters = self.sql(expression, "params_struct")
4017        return self.func("PREDICT", model, table, parameters or None)
def forin_sql(self, expression: sqlglot.expressions.ForIn) -> str:
4019    def forin_sql(self, expression: exp.ForIn) -> str:
4020        this = self.sql(expression, "this")
4021        expression_sql = self.sql(expression, "expression")
4022        return f"FOR {this} DO {expression_sql}"
def refresh_sql(self, expression: sqlglot.expressions.Refresh) -> str:
4024    def refresh_sql(self, expression: exp.Refresh) -> str:
4025        this = self.sql(expression, "this")
4026        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4027        return f"REFRESH {table}{this}"
def toarray_sql(self, expression: sqlglot.expressions.ToArray) -> str:
4029    def toarray_sql(self, expression: exp.ToArray) -> str:
4030        arg = expression.this
4031        if not arg.type:
4032            from sqlglot.optimizer.annotate_types import annotate_types
4033
4034            arg = annotate_types(arg, dialect=self.dialect)
4035
4036        if arg.is_type(exp.DataType.Type.ARRAY):
4037            return self.sql(arg)
4038
4039        cond_for_null = arg.is_(exp.null())
4040        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
def tsordstotime_sql(self, expression: sqlglot.expressions.TsOrDsToTime) -> str:
4042    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4043        this = expression.this
4044        time_format = self.format_time(expression)
4045
4046        if time_format:
4047            return self.sql(
4048                exp.cast(
4049                    exp.StrToTime(this=this, format=expression.args["format"]),
4050                    exp.DataType.Type.TIME,
4051                )
4052            )
4053
4054        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4055            return self.sql(this)
4056
4057        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
def tsordstotimestamp_sql(self, expression: sqlglot.expressions.TsOrDsToTimestamp) -> str:
4059    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4060        this = expression.this
4061        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4062            return self.sql(this)
4063
4064        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
def tsordstodatetime_sql(self, expression: sqlglot.expressions.TsOrDsToDatetime) -> str:
4066    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4067        this = expression.this
4068        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4069            return self.sql(this)
4070
4071        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
def tsordstodate_sql(self, expression: sqlglot.expressions.TsOrDsToDate) -> str:
4073    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4074        this = expression.this
4075        time_format = self.format_time(expression)
4076
4077        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4078            return self.sql(
4079                exp.cast(
4080                    exp.StrToTime(this=this, format=expression.args["format"]),
4081                    exp.DataType.Type.DATE,
4082                )
4083            )
4084
4085        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4086            return self.sql(this)
4087
4088        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
def unixdate_sql(self, expression: sqlglot.expressions.UnixDate) -> str:
4090    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4091        return self.sql(
4092            exp.func(
4093                "DATEDIFF",
4094                expression.this,
4095                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4096                "day",
4097            )
4098        )
def lastday_sql(self, expression: sqlglot.expressions.LastDay) -> str:
4100    def lastday_sql(self, expression: exp.LastDay) -> str:
4101        if self.LAST_DAY_SUPPORTS_DATE_PART:
4102            return self.function_fallback_sql(expression)
4103
4104        unit = expression.text("unit")
4105        if unit and unit != "MONTH":
4106            self.unsupported("Date parts are not supported in LAST_DAY.")
4107
4108        return self.func("LAST_DAY", expression.this)
def dateadd_sql(self, expression: sqlglot.expressions.DateAdd) -> str:
4110    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4111        from sqlglot.dialects.dialect import unit_to_str
4112
4113        return self.func(
4114            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4115        )
def arrayany_sql(self, expression: sqlglot.expressions.ArrayAny) -> str:
4117    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4118        if self.CAN_IMPLEMENT_ARRAY_ANY:
4119            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4120            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4121            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4122            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4123
4124        from sqlglot.dialects import Dialect
4125
4126        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4127        if self.dialect.__class__ != Dialect:
4128            self.unsupported("ARRAY_ANY is unsupported")
4129
4130        return self.function_fallback_sql(expression)
def struct_sql(self, expression: sqlglot.expressions.Struct) -> str:
4132    def struct_sql(self, expression: exp.Struct) -> str:
4133        expression.set(
4134            "expressions",
4135            [
4136                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4137                if isinstance(e, exp.PropertyEQ)
4138                else e
4139                for e in expression.expressions
4140            ],
4141        )
4142
4143        return self.function_fallback_sql(expression)
def partitionrange_sql(self, expression: sqlglot.expressions.PartitionRange) -> str:
4145    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4146        low = self.sql(expression, "this")
4147        high = self.sql(expression, "expression")
4148
4149        return f"{low} TO {high}"
def truncatetable_sql(self, expression: sqlglot.expressions.TruncateTable) -> str:
4151    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4152        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4153        tables = f" {self.expressions(expression)}"
4154
4155        exists = " IF EXISTS" if expression.args.get("exists") else ""
4156
4157        on_cluster = self.sql(expression, "cluster")
4158        on_cluster = f" {on_cluster}" if on_cluster else ""
4159
4160        identity = self.sql(expression, "identity")
4161        identity = f" {identity} IDENTITY" if identity else ""
4162
4163        option = self.sql(expression, "option")
4164        option = f" {option}" if option else ""
4165
4166        partition = self.sql(expression, "partition")
4167        partition = f" {partition}" if partition else ""
4168
4169        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
def convert_sql(self, expression: sqlglot.expressions.Convert) -> str:
4173    def convert_sql(self, expression: exp.Convert) -> str:
4174        to = expression.this
4175        value = expression.expression
4176        style = expression.args.get("style")
4177        safe = expression.args.get("safe")
4178        strict = expression.args.get("strict")
4179
4180        if not to or not value:
4181            return ""
4182
4183        # Retrieve length of datatype and override to default if not specified
4184        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4185            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4186
4187        transformed: t.Optional[exp.Expression] = None
4188        cast = exp.Cast if strict else exp.TryCast
4189
4190        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4191        if isinstance(style, exp.Literal) and style.is_int:
4192            from sqlglot.dialects.tsql import TSQL
4193
4194            style_value = style.name
4195            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4196            if not converted_style:
4197                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4198
4199            fmt = exp.Literal.string(converted_style)
4200
4201            if to.this == exp.DataType.Type.DATE:
4202                transformed = exp.StrToDate(this=value, format=fmt)
4203            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4204                transformed = exp.StrToTime(this=value, format=fmt)
4205            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4206                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4207            elif to.this == exp.DataType.Type.TEXT:
4208                transformed = exp.TimeToStr(this=value, format=fmt)
4209
4210        if not transformed:
4211            transformed = cast(this=value, to=to, safe=safe)
4212
4213        return self.sql(transformed)
def copyparameter_sql(self, expression: sqlglot.expressions.CopyParameter) -> str:
4273    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4274        option = self.sql(expression, "this")
4275
4276        if expression.expressions:
4277            upper = option.upper()
4278
4279            # Snowflake FILE_FORMAT options are separated by whitespace
4280            sep = " " if upper == "FILE_FORMAT" else ", "
4281
4282            # Databricks copy/format options do not set their list of values with EQ
4283            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4284            values = self.expressions(expression, flat=True, sep=sep)
4285            return f"{option}{op}({values})"
4286
4287        value = self.sql(expression, "expression")
4288
4289        if not value:
4290            return option
4291
4292        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4293
4294        return f"{option}{op}{value}"
def credentials_sql(self, expression: sqlglot.expressions.Credentials) -> str:
4296    def credentials_sql(self, expression: exp.Credentials) -> str:
4297        cred_expr = expression.args.get("credentials")
4298        if isinstance(cred_expr, exp.Literal):
4299            # Redshift case: CREDENTIALS <string>
4300            credentials = self.sql(expression, "credentials")
4301            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4302        else:
4303            # Snowflake case: CREDENTIALS = (...)
4304            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4305            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4306
4307        storage = self.sql(expression, "storage")
4308        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4309
4310        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4311        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4312
4313        iam_role = self.sql(expression, "iam_role")
4314        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4315
4316        region = self.sql(expression, "region")
4317        region = f" REGION {region}" if region else ""
4318
4319        return f"{credentials}{storage}{encryption}{iam_role}{region}"
def copy_sql(self, expression: sqlglot.expressions.Copy) -> str:
4321    def copy_sql(self, expression: exp.Copy) -> str:
4322        this = self.sql(expression, "this")
4323        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4324
4325        credentials = self.sql(expression, "credentials")
4326        credentials = self.seg(credentials) if credentials else ""
4327        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4328        files = self.expressions(expression, key="files", flat=True)
4329
4330        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4331        params = self.expressions(
4332            expression,
4333            key="params",
4334            sep=sep,
4335            new_line=True,
4336            skip_last=True,
4337            skip_first=True,
4338            indent=self.COPY_PARAMS_ARE_WRAPPED,
4339        )
4340
4341        if params:
4342            if self.COPY_PARAMS_ARE_WRAPPED:
4343                params = f" WITH ({params})"
4344            elif not self.pretty:
4345                params = f" {params}"
4346
4347        return f"COPY{this}{kind} {files}{credentials}{params}"
def semicolon_sql(self, expression: sqlglot.expressions.Semicolon) -> str:
4349    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4350        return ""
def datadeletionproperty_sql(self, expression: sqlglot.expressions.DataDeletionProperty) -> str:
4352    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4353        on_sql = "ON" if expression.args.get("on") else "OFF"
4354        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4355        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4356        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4357        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4358
4359        if filter_col or retention_period:
4360            on_sql = self.func("ON", filter_col, retention_period)
4361
4362        return f"DATA_DELETION={on_sql}"
def maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4364    def maskingpolicycolumnconstraint_sql(
4365        self, expression: exp.MaskingPolicyColumnConstraint
4366    ) -> str:
4367        this = self.sql(expression, "this")
4368        expressions = self.expressions(expression, flat=True)
4369        expressions = f" USING ({expressions})" if expressions else ""
4370        return f"MASKING POLICY {this}{expressions}"
def gapfill_sql(self, expression: sqlglot.expressions.GapFill) -> str:
4372    def gapfill_sql(self, expression: exp.GapFill) -> str:
4373        this = self.sql(expression, "this")
4374        this = f"TABLE {this}"
4375        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
def scope_resolution(self, rhs: str, scope_name: str) -> str:
4377    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4378        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
def scoperesolution_sql(self, expression: sqlglot.expressions.ScopeResolution) -> str:
4380    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4381        this = self.sql(expression, "this")
4382        expr = expression.expression
4383
4384        if isinstance(expr, exp.Func):
4385            # T-SQL's CLR functions are case sensitive
4386            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4387        else:
4388            expr = self.sql(expression, "expression")
4389
4390        return self.scope_resolution(expr, this)
def parsejson_sql(self, expression: sqlglot.expressions.ParseJSON) -> str:
4392    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4393        if self.PARSE_JSON_NAME is None:
4394            return self.sql(expression.this)
4395
4396        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
def rand_sql(self, expression: sqlglot.expressions.Rand) -> str:
4398    def rand_sql(self, expression: exp.Rand) -> str:
4399        lower = self.sql(expression, "lower")
4400        upper = self.sql(expression, "upper")
4401
4402        if lower and upper:
4403            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4404        return self.func("RAND", expression.this)
def changes_sql(self, expression: sqlglot.expressions.Changes) -> str:
4406    def changes_sql(self, expression: exp.Changes) -> str:
4407        information = self.sql(expression, "information")
4408        information = f"INFORMATION => {information}"
4409        at_before = self.sql(expression, "at_before")
4410        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4411        end = self.sql(expression, "end")
4412        end = f"{self.seg('')}{end}" if end else ""
4413
4414        return f"CHANGES ({information}){at_before}{end}"
def pad_sql(self, expression: sqlglot.expressions.Pad) -> str:
4416    def pad_sql(self, expression: exp.Pad) -> str:
4417        prefix = "L" if expression.args.get("is_left") else "R"
4418
4419        fill_pattern = self.sql(expression, "fill_pattern") or None
4420        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4421            fill_pattern = "' '"
4422
4423        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def summarize_sql(self, expression: sqlglot.expressions.Summarize) -> str:
4425    def summarize_sql(self, expression: exp.Summarize) -> str:
4426        table = " TABLE" if expression.args.get("table") else ""
4427        return f"SUMMARIZE{table} {self.sql(expression.this)}"
def explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4429    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4430        generate_series = exp.GenerateSeries(**expression.args)
4431
4432        parent = expression.parent
4433        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4434            parent = parent.parent
4435
4436        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4437            return self.sql(exp.Unnest(expressions=[generate_series]))
4438
4439        if isinstance(parent, exp.Select):
4440            self.unsupported("GenerateSeries projection unnesting is not supported.")
4441
4442        return self.sql(generate_series)
def arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4444    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4445        exprs = expression.expressions
4446        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4447            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4448        else:
4449            rhs = self.expressions(expression)
4450
4451        return self.func(name, expression.this, rhs or None)
def converttimezone_sql(self, expression: sqlglot.expressions.ConvertTimezone) -> str:
4453    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4454        if self.SUPPORTS_CONVERT_TIMEZONE:
4455            return self.function_fallback_sql(expression)
4456
4457        source_tz = expression.args.get("source_tz")
4458        target_tz = expression.args.get("target_tz")
4459        timestamp = expression.args.get("timestamp")
4460
4461        if source_tz and timestamp:
4462            timestamp = exp.AtTimeZone(
4463                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4464            )
4465
4466        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4467
4468        return self.sql(expr)
def json_sql(self, expression: sqlglot.expressions.JSON) -> str:
4470    def json_sql(self, expression: exp.JSON) -> str:
4471        this = self.sql(expression, "this")
4472        this = f" {this}" if this else ""
4473
4474        _with = expression.args.get("with")
4475
4476        if _with is None:
4477            with_sql = ""
4478        elif not _with:
4479            with_sql = " WITHOUT"
4480        else:
4481            with_sql = " WITH"
4482
4483        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4484
4485        return f"JSON{this}{with_sql}{unique_sql}"
def jsonvalue_sql(self, expression: sqlglot.expressions.JSONValue) -> str:
4487    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4488        def _generate_on_options(arg: t.Any) -> str:
4489            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4490
4491        path = self.sql(expression, "path")
4492        returning = self.sql(expression, "returning")
4493        returning = f" RETURNING {returning}" if returning else ""
4494
4495        on_condition = self.sql(expression, "on_condition")
4496        on_condition = f" {on_condition}" if on_condition else ""
4497
4498        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
def conditionalinsert_sql(self, expression: sqlglot.expressions.ConditionalInsert) -> str:
4500    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4501        else_ = "ELSE " if expression.args.get("else_") else ""
4502        condition = self.sql(expression, "expression")
4503        condition = f"WHEN {condition} THEN " if condition else else_
4504        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4505        return f"{condition}{insert}"
def multitableinserts_sql(self, expression: sqlglot.expressions.MultitableInserts) -> str:
4507    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4508        kind = self.sql(expression, "kind")
4509        expressions = self.seg(self.expressions(expression, sep=" "))
4510        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4511        return res
def oncondition_sql(self, expression: sqlglot.expressions.OnCondition) -> str:
4513    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4514        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4515        empty = expression.args.get("empty")
4516        empty = (
4517            f"DEFAULT {empty} ON EMPTY"
4518            if isinstance(empty, exp.Expression)
4519            else self.sql(expression, "empty")
4520        )
4521
4522        error = expression.args.get("error")
4523        error = (
4524            f"DEFAULT {error} ON ERROR"
4525            if isinstance(error, exp.Expression)
4526            else self.sql(expression, "error")
4527        )
4528
4529        if error and empty:
4530            error = (
4531                f"{empty} {error}"
4532                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4533                else f"{error} {empty}"
4534            )
4535            empty = ""
4536
4537        null = self.sql(expression, "null")
4538
4539        return f"{empty}{error}{null}"
def jsonextractquote_sql(self, expression: sqlglot.expressions.JSONExtractQuote) -> str:
4541    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4542        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4543        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
def jsonexists_sql(self, expression: sqlglot.expressions.JSONExists) -> str:
4545    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4546        this = self.sql(expression, "this")
4547        path = self.sql(expression, "path")
4548
4549        passing = self.expressions(expression, "passing")
4550        passing = f" PASSING {passing}" if passing else ""
4551
4552        on_condition = self.sql(expression, "on_condition")
4553        on_condition = f" {on_condition}" if on_condition else ""
4554
4555        path = f"{path}{passing}{on_condition}"
4556
4557        return self.func("JSON_EXISTS", this, path)
def arrayagg_sql(self, expression: sqlglot.expressions.ArrayAgg) -> str:
4559    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4560        array_agg = self.function_fallback_sql(expression)
4561
4562        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4563        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4564        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4565            parent = expression.parent
4566            if isinstance(parent, exp.Filter):
4567                parent_cond = parent.expression.this
4568                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4569            else:
4570                this = expression.this
4571                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4572                if this.find(exp.Column):
4573                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4574                    this_sql = (
4575                        self.expressions(this)
4576                        if isinstance(this, exp.Distinct)
4577                        else self.sql(expression, "this")
4578                    )
4579
4580                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4581
4582        return array_agg
def apply_sql(self, expression: sqlglot.expressions.Apply) -> str:
4584    def apply_sql(self, expression: exp.Apply) -> str:
4585        this = self.sql(expression, "this")
4586        expr = self.sql(expression, "expression")
4587
4588        return f"{this} APPLY({expr})"
def grant_sql(self, expression: sqlglot.expressions.Grant) -> str:
4590    def grant_sql(self, expression: exp.Grant) -> str:
4591        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4592
4593        kind = self.sql(expression, "kind")
4594        kind = f" {kind}" if kind else ""
4595
4596        securable = self.sql(expression, "securable")
4597        securable = f" {securable}" if securable else ""
4598
4599        principals = self.expressions(expression, key="principals", flat=True)
4600
4601        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4602
4603        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
def grantprivilege_sql(self, expression: sqlglot.expressions.GrantPrivilege):
4605    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4606        this = self.sql(expression, "this")
4607        columns = self.expressions(expression, flat=True)
4608        columns = f"({columns})" if columns else ""
4609
4610        return f"{this}{columns}"
def grantprincipal_sql(self, expression: sqlglot.expressions.GrantPrincipal):
4612    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4613        this = self.sql(expression, "this")
4614
4615        kind = self.sql(expression, "kind")
4616        kind = f"{kind} " if kind else ""
4617
4618        return f"{kind}{this}"
def columns_sql(self, expression: sqlglot.expressions.Columns):
4620    def columns_sql(self, expression: exp.Columns):
4621        func = self.function_fallback_sql(expression)
4622        if expression.args.get("unpack"):
4623            func = f"*{func}"
4624
4625        return func
def overlay_sql(self, expression: sqlglot.expressions.Overlay):
4627    def overlay_sql(self, expression: exp.Overlay):
4628        this = self.sql(expression, "this")
4629        expr = self.sql(expression, "expression")
4630        from_sql = self.sql(expression, "from")
4631        for_sql = self.sql(expression, "for")
4632        for_sql = f" FOR {for_sql}" if for_sql else ""
4633
4634        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4636    @unsupported_args("format")
4637    def todouble_sql(self, expression: exp.ToDouble) -> str:
4638        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
def string_sql(self, expression: sqlglot.expressions.String) -> str:
4640    def string_sql(self, expression: exp.String) -> str:
4641        this = expression.this
4642        zone = expression.args.get("zone")
4643
4644        if zone:
4645            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4646            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4647            # set for source_tz to transpile the time conversion before the STRING cast
4648            this = exp.ConvertTimezone(
4649                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4650            )
4651
4652        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def median_sql(self, expression: sqlglot.expressions.Median):
4654    def median_sql(self, expression: exp.Median):
4655        if not self.SUPPORTS_MEDIAN:
4656            return self.sql(
4657                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4658            )
4659
4660        return self.function_fallback_sql(expression)
def overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4662    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4663        filler = self.sql(expression, "this")
4664        filler = f" {filler}" if filler else ""
4665        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4666        return f"TRUNCATE{filler} {with_count}"
def unixseconds_sql(self, expression: sqlglot.expressions.UnixSeconds) -> str:
4668    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4669        if self.SUPPORTS_UNIX_SECONDS:
4670            return self.function_fallback_sql(expression)
4671
4672        start_ts = exp.cast(
4673            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4674        )
4675
4676        return self.sql(
4677            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4678        )
def arraysize_sql(self, expression: sqlglot.expressions.ArraySize) -> str:
4680    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4681        dim = expression.expression
4682
4683        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4684        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4685            if not (dim.is_int and dim.name == "1"):
4686                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4687            dim = None
4688
4689        # If dimension is required but not specified, default initialize it
4690        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4691            dim = exp.Literal.number(1)
4692
4693        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
def attach_sql(self, expression: sqlglot.expressions.Attach) -> str:
4695    def attach_sql(self, expression: exp.Attach) -> str:
4696        this = self.sql(expression, "this")
4697        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4698        expressions = self.expressions(expression)
4699        expressions = f" ({expressions})" if expressions else ""
4700
4701        return f"ATTACH{exists_sql} {this}{expressions}"
def detach_sql(self, expression: sqlglot.expressions.Detach) -> str:
4703    def detach_sql(self, expression: exp.Detach) -> str:
4704        this = self.sql(expression, "this")
4705        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4706
4707        return f"DETACH{exists_sql} {this}"
def attachoption_sql(self, expression: sqlglot.expressions.AttachOption) -> str:
4709    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4710        this = self.sql(expression, "this")
4711        value = self.sql(expression, "expression")
4712        value = f" {value}" if value else ""
4713        return f"{this}{value}"
def featuresattime_sql(self, expression: sqlglot.expressions.FeaturesAtTime) -> str:
4715    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4716        this_sql = self.sql(expression, "this")
4717        if isinstance(expression.this, exp.Table):
4718            this_sql = f"TABLE {this_sql}"
4719
4720        return self.func(
4721            "FEATURES_AT_TIME",
4722            this_sql,
4723            expression.args.get("time"),
4724            expression.args.get("num_rows"),
4725            expression.args.get("ignore_feature_nulls"),
4726        )
def watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4728    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4729        return (
4730            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4731        )
def encodeproperty_sql(self, expression: sqlglot.expressions.EncodeProperty) -> str:
4733    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4734        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4735        encode = f"{encode} {self.sql(expression, 'this')}"
4736
4737        properties = expression.args.get("properties")
4738        if properties:
4739            encode = f"{encode} {self.properties(properties)}"
4740
4741        return encode
def includeproperty_sql(self, expression: sqlglot.expressions.IncludeProperty) -> str:
4743    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4744        this = self.sql(expression, "this")
4745        include = f"INCLUDE {this}"
4746
4747        column_def = self.sql(expression, "column_def")
4748        if column_def:
4749            include = f"{include} {column_def}"
4750
4751        alias = self.sql(expression, "alias")
4752        if alias:
4753            include = f"{include} AS {alias}"
4754
4755        return include
def xmlelement_sql(self, expression: sqlglot.expressions.XMLElement) -> str:
4757    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4758        name = f"NAME {self.sql(expression, 'this')}"
4759        return self.func("XMLELEMENT", name, *expression.expressions)
def partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4761    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4762        partitions = self.expressions(expression, "partition_expressions")
4763        create = self.expressions(expression, "create_expressions")
4764        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4766    def partitionbyrangepropertydynamic_sql(
4767        self, expression: exp.PartitionByRangePropertyDynamic
4768    ) -> str:
4769        start = self.sql(expression, "start")
4770        end = self.sql(expression, "end")
4771
4772        every = expression.args["every"]
4773        if isinstance(every, exp.Interval) and every.this.is_string:
4774            every.this.replace(exp.Literal.number(every.name))
4775
4776        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
def unpivotcolumns_sql(self, expression: sqlglot.expressions.UnpivotColumns) -> str:
4778    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4779        name = self.sql(expression, "this")
4780        values = self.expressions(expression, flat=True)
4781
4782        return f"NAME {name} VALUE {values}"
def analyzesample_sql(self, expression: sqlglot.expressions.AnalyzeSample) -> str:
4784    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4785        kind = self.sql(expression, "kind")
4786        sample = self.sql(expression, "sample")
4787        return f"SAMPLE {sample} {kind}"
def analyzestatistics_sql(self, expression: sqlglot.expressions.AnalyzeStatistics) -> str:
4789    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4790        kind = self.sql(expression, "kind")
4791        option = self.sql(expression, "option")
4792        option = f" {option}" if option else ""
4793        this = self.sql(expression, "this")
4794        this = f" {this}" if this else ""
4795        columns = self.expressions(expression)
4796        columns = f" {columns}" if columns else ""
4797        return f"{kind}{option} STATISTICS{this}{columns}"
def analyzehistogram_sql(self, expression: sqlglot.expressions.AnalyzeHistogram) -> str:
4799    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4800        this = self.sql(expression, "this")
4801        columns = self.expressions(expression)
4802        inner_expression = self.sql(expression, "expression")
4803        inner_expression = f" {inner_expression}" if inner_expression else ""
4804        update_options = self.sql(expression, "update_options")
4805        update_options = f" {update_options} UPDATE" if update_options else ""
4806        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def analyzedelete_sql(self, expression: sqlglot.expressions.AnalyzeDelete) -> str:
4808    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4809        kind = self.sql(expression, "kind")
4810        kind = f" {kind}" if kind else ""
4811        return f"DELETE{kind} STATISTICS"
def analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4813    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4814        inner_expression = self.sql(expression, "expression")
4815        return f"LIST CHAINED ROWS{inner_expression}"
def analyzevalidate_sql(self, expression: sqlglot.expressions.AnalyzeValidate) -> str:
4817    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4818        kind = self.sql(expression, "kind")
4819        this = self.sql(expression, "this")
4820        this = f" {this}" if this else ""
4821        inner_expression = self.sql(expression, "expression")
4822        return f"VALIDATE {kind}{this}{inner_expression}"
def analyze_sql(self, expression: sqlglot.expressions.Analyze) -> str:
4824    def analyze_sql(self, expression: exp.Analyze) -> str:
4825        options = self.expressions(expression, key="options", sep=" ")
4826        options = f" {options}" if options else ""
4827        kind = self.sql(expression, "kind")
4828        kind = f" {kind}" if kind else ""
4829        this = self.sql(expression, "this")
4830        this = f" {this}" if this else ""
4831        mode = self.sql(expression, "mode")
4832        mode = f" {mode}" if mode else ""
4833        properties = self.sql(expression, "properties")
4834        properties = f" {properties}" if properties else ""
4835        partition = self.sql(expression, "partition")
4836        partition = f" {partition}" if partition else ""
4837        inner_expression = self.sql(expression, "expression")
4838        inner_expression = f" {inner_expression}" if inner_expression else ""
4839        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
def xmltable_sql(self, expression: sqlglot.expressions.XMLTable) -> str:
4841    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4842        this = self.sql(expression, "this")
4843        namespaces = self.expressions(expression, key="namespaces")
4844        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4845        passing = self.expressions(expression, key="passing")
4846        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4847        columns = self.expressions(expression, key="columns")
4848        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4849        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4850        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
def xmlnamespace_sql(self, expression: sqlglot.expressions.XMLNamespace) -> str:
4852    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4853        this = self.sql(expression, "this")
4854        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
def export_sql(self, expression: sqlglot.expressions.Export) -> str:
4856    def export_sql(self, expression: exp.Export) -> str:
4857        this = self.sql(expression, "this")
4858        connection = self.sql(expression, "connection")
4859        connection = f"WITH CONNECTION {connection} " if connection else ""
4860        options = self.sql(expression, "options")
4861        return f"EXPORT DATA {connection}{options} AS {this}"
def declare_sql(self, expression: sqlglot.expressions.Declare) -> str:
4863    def declare_sql(self, expression: exp.Declare) -> str:
4864        return f"DECLARE {self.expressions(expression, flat=True)}"
def declareitem_sql(self, expression: sqlglot.expressions.DeclareItem) -> str:
4866    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4867        variable = self.sql(expression, "this")
4868        default = self.sql(expression, "default")
4869        default = f" = {default}" if default else ""
4870
4871        kind = self.sql(expression, "kind")
4872        if isinstance(expression.args.get("kind"), exp.Schema):
4873            kind = f"TABLE {kind}"
4874
4875        return f"{variable} AS {kind}{default}"
def recursivewithsearch_sql(self, expression: sqlglot.expressions.RecursiveWithSearch) -> str:
4877    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4878        kind = self.sql(expression, "kind")
4879        this = self.sql(expression, "this")
4880        set = self.sql(expression, "expression")
4881        using = self.sql(expression, "using")
4882        using = f" USING {using}" if using else ""
4883
4884        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4885
4886        return f"{kind_sql} {this} SET {set}{using}"
def parameterizedagg_sql(self, expression: sqlglot.expressions.ParameterizedAgg) -> str:
4888    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4889        params = self.expressions(expression, key="params", flat=True)
4890        return self.func(expression.name, *expression.expressions) + f"({params})"
def anonymousaggfunc_sql(self, expression: sqlglot.expressions.AnonymousAggFunc) -> str:
4892    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4893        return self.func(expression.name, *expression.expressions)
def combinedaggfunc_sql(self, expression: sqlglot.expressions.CombinedAggFunc) -> str:
4895    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4896        return self.anonymousaggfunc_sql(expression)
def combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4898    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4899        return self.parameterizedagg_sql(expression)
def show_sql(self, expression: sqlglot.expressions.Show) -> str:
4901    def show_sql(self, expression: exp.Show) -> str:
4902        self.unsupported("Unsupported SHOW statement")
4903        return ""
def put_sql(self, expression: sqlglot.expressions.Put) -> str:
4905    def put_sql(self, expression: exp.Put) -> str:
4906        props = expression.args.get("properties")
4907        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4908        this = self.sql(expression, "this")
4909        target = self.sql(expression, "target")
4910        return f"PUT {this} {target}{props_sql}"